mirror of
https://github.com/Elysola/WebHooker.git
synced 2026-11-20 17:13:49 +00:00
fix(filters): preserve regex meaning when changing operators
Swap wrapped and raw regex sources only when both compile identically after saving. Leave literal, glob, multiline and Unicode-sensitive comparisons unchanged rather than inventing non-equivalent conversions.
This commit is contained in:
1 parent
2717ab49dc
commit
54b2944dd4
5 files changed
+129
-8
No files matched your search
@@ -5,6 +5,7 @@ import { FILTER_SCOPE_EVENTS, blankNode, isBlankNode, nodeKey } from "~/composab
|
||||
import { FILTER_TYPES, FILTER_OPS } from "~/types";
|
||||
import type { FilterOp, FilterType } from "~/types";
|
||||
import {
|
||||
convertValuesForOp,
|
||||
fieldPathOptions,
|
||||
isArrayFieldPath,
|
||||
validateFilterValue,
|
||||
@@ -58,17 +59,24 @@ function validateValue(value: string): string | null {
|
||||
return validateFilterValue(props.node.leaf.type, props.node.leaf.op, value);
|
||||
}
|
||||
|
||||
/** Switch the operator, swapping `/x/` ↔ `x` when moving to or from `regex`. */
|
||||
function changeOp(next: FilterOp): void {
|
||||
const { leaf } = props.node;
|
||||
leaf.values = convertValuesForOp(leaf.values, leaf.op, next);
|
||||
leaf.op = next;
|
||||
}
|
||||
|
||||
function setType(value: string): void {
|
||||
if ((FILTER_TYPES as readonly string[]).includes(value)) {
|
||||
props.node.leaf.type = value as FilterType;
|
||||
// Keyword filters have no operator; a hidden `exists` would drop their values.
|
||||
if (value === "keyword") props.node.leaf.op = "eq";
|
||||
if (value === "keyword") changeOp("eq");
|
||||
}
|
||||
}
|
||||
|
||||
function setOp(value: string): void {
|
||||
if (FILTER_OPS.includes(value as FilterOp)) {
|
||||
props.node.leaf.op = value as FilterOp;
|
||||
changeOp(value as FilterOp);
|
||||
// `exists` hides the values input: its unadded text must not block saving.
|
||||
if (!showValues.value) props.node.leaf.draft = "";
|
||||
}
|
||||
@@ -78,7 +86,7 @@ function setPath(value: string | string[]): void {
|
||||
props.node.leaf.path = typeof value === "string" ? value : "";
|
||||
// Paths ending on an array compare the whole array; `contains` matches an element.
|
||||
if (isArrayFieldPath(props.node.leaf.path) && props.node.leaf.op === "eq") {
|
||||
props.node.leaf.op = "contains";
|
||||
changeOp("contains");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1198,6 +1198,38 @@ function typeValueOptions(
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Operator changes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Operators whose values may be a wrapped `/regex/` (server `matchField`). */
|
||||
function readsWrappedRegex(op: FilterOp): boolean {
|
||||
return op === "eq" || op === "ne" || op === "in";
|
||||
}
|
||||
|
||||
/**
|
||||
* Values rewritten for a new operator where the rewrite matches exactly the
|
||||
* same: a wrapped `/x/` of the default operators and the raw `x` of `regex`
|
||||
* compile to the same server regex, so they are swapped (`/^v\d+/` ↔
|
||||
* `^v\d+`). Nothing else is rewritten — literal, glob and substring
|
||||
* comparisons differ from regexes on line breaks and Unicode case folding —
|
||||
* so other values stay as typed, and validation flags those that can never
|
||||
* match. Saving trims every value, so a source that is empty or starts/ends
|
||||
* with whitespace (`//`, `/ main /`) cannot stand alone and stays wrapped.
|
||||
*/
|
||||
export function convertValuesForOp(values: string[], from: FilterOp, to: FilterOp): string[] {
|
||||
if (readsWrappedRegex(from) && to === "regex") {
|
||||
return values.map((v) => {
|
||||
const value = v.trim();
|
||||
const source = value.slice(1, -1);
|
||||
return isWrappedRegex(value) && source && source === source.trim() ? source : v;
|
||||
});
|
||||
}
|
||||
if (from === "regex" && readsWrappedRegex(to))
|
||||
return values.map((v) => (v.trim() ? `/${v.trim()}/` : v));
|
||||
return values;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Validation (mirrors server/lib/events/filter-ast.ts)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -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 <kbd>Enter</kbd> 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.
|
||||
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 <kbd>Enter</kbd> 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. Switching between **equals** / **not equals** / **in** and **matches regex** rewrites `/x/` ↔ `x` in the values already added — both forms compile to the same regular expression, so the condition keeps matching exactly the same. Other values stay as typed (literal, glob and substring comparisons differ from regular expressions on line breaks and Unicode case folding), and values that can never match under the new operator are flagged. 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
|
||||
|
||||
|
||||
@@ -256,7 +256,7 @@
|
||||
|
||||
当 `ast` 存在时,它优先于 `filters`。管理后台的路由编辑器会以可视化方式构建 `ast`(all/any/not 分组)、实时展示树状解释,并可通过「测试匹配」面板粘贴 JSON 载荷进行试匹配。
|
||||
|
||||
匹配值、字段路径与测试事件均为可搜索的下拉框。候选项来自 GitHub 与 Gitea 的 webhook 定义——事件、路由所选事件的动作、常用载荷路径及其已知取值——以英文 key 展示,并附当前界面语言的说明;搜索优先匹配 key,其次匹配英文或中文说明。列表之外的值仍可直接输入,添加前会按匹配规则校验,只拒绝永远不可能匹配的值(含空格的事件名、含 git 禁用字符的分支、无效的正则、比较运算中的非数字等);仓库与操作者不做格式限制,因为自定义 webhook 可以携带任意字符串。已输入但未按<kbd>回车</kbd>添加的内容会阻止保存路由、存为片段和测试匹配,而不会被静默添加或丢弃。可一次输入或粘贴多个值,以逗号或换行分隔;`/正则/` 内的逗号会保留,选择「正则匹配」运算符时只按换行分隔(如 `^v{1,3}` 这样的原始模式可以包含逗号)。候选值会随运算符调整:「包含 / 开头是 / 结尾是」按字面比较,因此通配候选会换成其对应的文本(「开头是」用 `release/` 代替 `release/*`,「结尾是」用 `[bot]` 代替 `*[bot]`);「正则匹配」会把候选换成已转义并加锚点的等价正则(如 `^dependabot\[bot\]$`、`^release/`);比较运算符不提供候选。`field` 路径中途的数组会被展开,但以数组**结尾**的路径(如 `commits.modified`)会作为整体比较——要匹配其中某个元素请用「包含」;在编辑器中选择这类候选路径时会自动切换为「包含」。
|
||||
匹配值、字段路径与测试事件均为可搜索的下拉框。候选项来自 GitHub 与 Gitea 的 webhook 定义——事件、路由所选事件的动作、常用载荷路径及其已知取值——以英文 key 展示,并附当前界面语言的说明;搜索优先匹配 key,其次匹配英文或中文说明。列表之外的值仍可直接输入,添加前会按匹配规则校验,只拒绝永远不可能匹配的值(含空格的事件名、含 git 禁用字符的分支、无效的正则、比较运算中的非数字等);仓库与操作者不做格式限制,因为自定义 webhook 可以携带任意字符串。已输入但未按<kbd>回车</kbd>添加的内容会阻止保存路由、存为片段和测试匹配,而不会被静默添加或丢弃。可一次输入或粘贴多个值,以逗号或换行分隔;`/正则/` 内的逗号会保留,选择「正则匹配」运算符时只按换行分隔(如 `^v{1,3}` 这样的原始模式可以包含逗号)。候选值会随运算符调整:「包含 / 开头是 / 结尾是」按字面比较,因此通配候选会换成其对应的文本(「开头是」用 `release/` 代替 `release/*`,「结尾是」用 `[bot]` 代替 `*[bot]`);「正则匹配」会把候选换成已转义并加锚点的等价正则(如 `^dependabot\[bot\]$`、`^release/`);比较运算符不提供候选。在「等于 / 不等于 / 属于」与「正则匹配」之间切换时,已添加的值会做 `/x/` ↔ `x` 改写——两种写法编译成同一个正则,匹配结果完全不变。其他值保持原样(字面、通配与按字面比较在换行和 Unicode 大小写折叠上与正则并不等价),在新运算符下永远无法匹配的值会被标出。`field` 路径中途的数组会被展开,但以数组**结尾**的路径(如 `commits.modified`)会作为整体比较——要匹配其中某个元素请用「包含」;在编辑器中选择这类候选路径时会自动切换为「包含」。
|
||||
|
||||
### 命名过滤器片段
|
||||
|
||||
|
||||
@@ -2,17 +2,18 @@ import { describe, it, expect } from "bun:test";
|
||||
import {
|
||||
actionOptions,
|
||||
commaEndsValue,
|
||||
splitFilterValues,
|
||||
convertValuesForOp,
|
||||
eventOptions,
|
||||
fieldPathOptions,
|
||||
fieldValueOptions,
|
||||
isArrayFieldPath,
|
||||
splitFilterValues,
|
||||
validateFilterValue,
|
||||
valueOptions,
|
||||
} from "../app/utils/filter-catalog";
|
||||
|
||||
import { formToLeaf } from "../app/composables/useFilterNode";
|
||||
import { evaluateFilterNode } from "../server/lib/events/filter-ast";
|
||||
import type { WebhookEvent } from "../server/lib/types";
|
||||
import type { FilterOp, WebhookEvent } from "../server/lib/types";
|
||||
|
||||
function values(opts: { value: string }[]): string[] {
|
||||
return opts.map((o) => o.value);
|
||||
@@ -229,6 +230,86 @@ describe("splitFilterValues", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("convertValuesForOp", () => {
|
||||
// Branch names and payload text, including line breaks and Unicode case
|
||||
// variants (Kelvin sign, final sigma) that literal and regex comparisons fold
|
||||
// differently.
|
||||
const subjects = [
|
||||
"main",
|
||||
" main ",
|
||||
"Main",
|
||||
"mainline",
|
||||
"release/v1",
|
||||
"release/a\u2028b",
|
||||
"build\nagent",
|
||||
"please run ci\nthanks",
|
||||
"\u212A",
|
||||
"k",
|
||||
"\u03C2",
|
||||
"\u03A3",
|
||||
];
|
||||
const actor = (login: string): WebhookEvent => ({
|
||||
event: "push",
|
||||
payload: { sender: { login } },
|
||||
});
|
||||
/** Subjects the condition matches once saved (the form trims every value). */
|
||||
const matched = (op: FilterOp, value: string): string[] => {
|
||||
const filter = formToLeaf({
|
||||
type: "actor",
|
||||
path: "",
|
||||
op,
|
||||
values: [value],
|
||||
exclude: false,
|
||||
draft: "",
|
||||
});
|
||||
return filter ? subjects.filter((s) => evaluateFilterNode(filter, actor(s))) : [];
|
||||
};
|
||||
|
||||
it("swaps a wrapped regex and the raw regex, which match exactly the same", () => {
|
||||
const cases: Array<[FilterOp, FilterOp, string, string]> = [
|
||||
["eq", "regex", "/^main/", "^main"],
|
||||
["ne", "regex", "/ci$/", "ci$"],
|
||||
["in", "regex", "/k/", "k"],
|
||||
["eq", "regex", "/\u03A3/", "\u03A3"],
|
||||
["regex", "eq", "^release/", "/^release//"],
|
||||
["regex", "in", "run ci", "/run ci/"],
|
||||
["regex", "eq", "/api/", "//api//"],
|
||||
];
|
||||
for (const [from, to, value, expected] of cases) {
|
||||
const [converted] = convertValuesForOp([value], from, to);
|
||||
expect(converted).toBe(expected);
|
||||
// `ne` negates per value; compare the value's own matches through `eq`.
|
||||
const plain = (op: FilterOp): FilterOp => (op === "ne" ? "eq" : op);
|
||||
expect(matched(plain(to), converted!)).toEqual(matched(plain(from), value));
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps wrapped sources that saving would change", () => {
|
||||
// Saving trims values: `/ main /` must not become `main`, nor `//` empty.
|
||||
for (const value of ["/ main /", "/main /", "//"]) {
|
||||
expect(convertValuesForOp([value], "eq", "regex")).toEqual([value]);
|
||||
}
|
||||
expect(matched("eq", "/ main /")).toEqual([" main "]);
|
||||
expect(convertValuesForOp([" "], "regex", "eq")).toEqual([" "]);
|
||||
});
|
||||
|
||||
it("keeps every other value as typed", () => {
|
||||
// Literal, glob and substring values have no exact regex equivalent.
|
||||
const values = ["main", "release/*", "*[bot]", "k"];
|
||||
const pairs: Array<[FilterOp, FilterOp]> = [
|
||||
["eq", "regex"],
|
||||
["eq", "startsWith"],
|
||||
["contains", "eq"],
|
||||
["contains", "regex"],
|
||||
["gt", "eq"],
|
||||
["eq", "ne"],
|
||||
];
|
||||
for (const [from, to] of pairs) expect(convertValuesForOp(values, from, to)).toEqual(values);
|
||||
expect(convertValuesForOp(["/x/"], "eq", "contains")).toEqual(["/x/"]);
|
||||
expect(convertValuesForOp(["^main"], "regex", "startsWith")).toEqual(["^main"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("commaEndsValue", () => {
|
||||
it("ends a value only when the comma is typed at its end", () => {
|
||||
expect(commaEndsValue("push", 4, 4)).toBe(true);
|
||||
|
||||
Reference in new issue
Block a user