mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-28 08:06:16 +00:00
fix: match folder run-as rules as the server does, and preselect them on deploy
Clients matched folder default_permissioned_as globs with minimatch, where `*` stops at `/`; the server uses globset defaults, where it does not. Now that clients send the rule they preview, a disagreement stored the wrong identity, so the frontend and CLI match with the server's semantics. Compare & Deploy and Deploy workspaces preselect the target folder's rule for an item new there. A group rule is sent by principal alone, since the address it falls back to contradicts the principal. A new script or flow keeps its seeded identity once its first deploy ends creation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
0b457a9529
commit
fa253bc50b
@@ -291,10 +291,10 @@ const command = new Command()
|
||||
}
|
||||
const relative = testPath.slice(prefix.length);
|
||||
|
||||
const { minimatch } = await import("minimatch");
|
||||
const { folderRuleGlobMatches } = await import("../../utils/folder_rule_glob.ts");
|
||||
for (let i = 0; i < rules.length; i++) {
|
||||
const rule = rules[i];
|
||||
if (minimatch(relative, rule.path_glob)) {
|
||||
if (folderRuleGlobMatches(rule.path_glob, relative)) {
|
||||
if (opts.json) {
|
||||
console.log(JSON.stringify({ matched: true, rule_index: i, rule, relative_path: relative }));
|
||||
} else {
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
} from "yaml";
|
||||
import JSZip from "jszip";
|
||||
import { minimatch } from "minimatch";
|
||||
import { folderRuleGlobMatches } from "../../utils/folder_rule_glob.ts";
|
||||
import { yamlParseContent, yamlParseFile } from "../../utils/yaml.ts";
|
||||
import * as wmill from "../../../gen/services.gen.ts";
|
||||
|
||||
@@ -5738,7 +5739,7 @@ export async function push(
|
||||
const relative = remotePath.slice(`f/${folderName}/`.length);
|
||||
if (!relative) continue;
|
||||
for (const rule of rules) {
|
||||
if (minimatch(relative, rule.path_glob)) {
|
||||
if (folderRuleGlobMatches(rule.path_glob, relative)) {
|
||||
folderDefaultAnnotations.set(change.path, rule.permissioned_as);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
} from "../utils/resource_folders.ts";
|
||||
import { deploysWithRawApp } from "../utils/app_files.ts";
|
||||
import { parseSyncBehavior } from "./conf.ts";
|
||||
import { minimatch } from "minimatch";
|
||||
import { folderRuleGlobMatches } from "../utils/folder_rule_glob.ts";
|
||||
|
||||
export interface PermissionedAsContext {
|
||||
userCache: Map<string, { username: string; email: string }>;
|
||||
@@ -78,13 +78,7 @@ async function folderRuleMatches(workspace: string, path: string): Promise<boole
|
||||
.catch(() => []);
|
||||
folderRules.set(key, rules);
|
||||
}
|
||||
return (await rules).some((r) => {
|
||||
try {
|
||||
return minimatch(m[2], r.path_glob);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return (await rules).some((r) => folderRuleGlobMatches(r.path_glob, m[2]));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Whether a folder `default_permissioned_as` glob matches a path relative to its folder, with
|
||||
* the semantics the server applies (`globset::Glob` defaults): `*` and `?` also match `/`,
|
||||
* `**` spans any depth, `{a,b}` alternates, `[!x]` negates, and an invalid glob matches nothing.
|
||||
* A push names its deployer where no rule matches, so a matcher that disagrees with the server
|
||||
* makes that name override the rule the server would have applied.
|
||||
*/
|
||||
export function folderRuleGlobMatches(glob: string, relativePath: string): boolean {
|
||||
const source = globToRegexSource(glob);
|
||||
return source !== undefined && new RegExp(`^${source}$`, "s").test(relativePath);
|
||||
}
|
||||
|
||||
function globToRegexSource(glob: string): string | undefined {
|
||||
let re = "";
|
||||
for (let i = 0; i < glob.length; i++) {
|
||||
const c = glob[i];
|
||||
if (c === "*") {
|
||||
if (glob[i + 1] !== "*") {
|
||||
re += ".*";
|
||||
continue;
|
||||
}
|
||||
const atSegmentStart = i === 0 || glob[i - 1] === "/";
|
||||
i++;
|
||||
if (atSegmentStart && glob[i + 1] === "/" && i + 2 < glob.length) {
|
||||
re += "(?:.*/)?";
|
||||
i++;
|
||||
} else {
|
||||
re += ".*";
|
||||
if (glob[i + 1] === "/") i++;
|
||||
}
|
||||
} else if (c === "?") {
|
||||
re += ".";
|
||||
} else if (c === "[") {
|
||||
const end = glob.indexOf("]", i + 2);
|
||||
if (end < 0) return undefined;
|
||||
let body = glob.slice(i + 1, end).replace(/[\\^]/g, "\\$&");
|
||||
if (body.startsWith("!")) body = "^" + body.slice(1);
|
||||
re += `[${body}]`;
|
||||
i = end;
|
||||
} else if (c === "{") {
|
||||
const end = glob.indexOf("}", i);
|
||||
if (end < 0) return undefined;
|
||||
const alternatives = glob
|
||||
.slice(i + 1, end)
|
||||
.split(",")
|
||||
.map(globToRegexSource);
|
||||
if (alternatives.some((a) => a === undefined)) return undefined;
|
||||
re += `(?:${alternatives.join("|")})`;
|
||||
i = end;
|
||||
} else if (c === "\\" && i + 1 < glob.length) {
|
||||
re += escapeRegex(glob[++i]);
|
||||
} else {
|
||||
re += escapeRegex(c);
|
||||
}
|
||||
}
|
||||
return re;
|
||||
}
|
||||
|
||||
function escapeRegex(c: string): string {
|
||||
return c.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { folderRuleGlobMatches } from "../src/utils/folder_rule_glob.ts";
|
||||
|
||||
// Expected matches are what `globset::Glob::new(glob).compile_matcher()` answers on the server.
|
||||
const PATHS = ["x", "jobs/a", "jobs/a/b", "a/b", "a/x/b", "a/c", "abc", "foo/z", "bar/z/q", "baz/z"];
|
||||
const CASES: [string, string[]][] = [
|
||||
["**", PATHS],
|
||||
["*", PATHS],
|
||||
["**/", PATHS],
|
||||
["jobs/*", ["jobs/a", "jobs/a/b"]],
|
||||
["a/**/b", ["a/b", "a/x/b"]],
|
||||
["**/x", ["x"]],
|
||||
["a?c", ["a/c", "abc"]],
|
||||
["[!ab]*", ["x", "jobs/a", "jobs/a/b", "foo/z"]],
|
||||
["{foo,bar}/*", ["foo/z", "bar/z/q"]],
|
||||
["[unclosed", []],
|
||||
];
|
||||
|
||||
describe("folderRuleGlobMatches", () => {
|
||||
for (const [glob, expected] of CASES) {
|
||||
test(`${glob} matches what the server matches`, () => {
|
||||
expect(PATHS.filter((p) => folderRuleGlobMatches(glob, p))).toEqual(expected);
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -60,6 +60,7 @@
|
||||
type OnBehalfOfChoice,
|
||||
type OnBehalfOfDetails
|
||||
} from './OnBehalfOfSelector.svelte'
|
||||
import { createFolderDefaultLookup } from './useFolderDefaultPermissionedAs.svelte'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { deepEqual } from 'fast-equals'
|
||||
import WorkspaceDeployLayout from './WorkspaceDeployLayout.svelte'
|
||||
@@ -500,6 +501,8 @@
|
||||
let onBehalfOfInfo = $state<Record<string, string | undefined>>({})
|
||||
let onBehalfOfChoice = $state<Record<string, OnBehalfOfChoice>>({})
|
||||
let customOnBehalfOf = $state<Record<string, OnBehalfOfDetails>>({})
|
||||
// An item new in the target takes the target folder's rule unless the deploy names someone.
|
||||
const targetFolderDefault = createFolderDefaultLookup()
|
||||
let deployTargetWorkspace = $derived(mergeIntoParent ? parentWorkspaceId : currentWorkspaceId)
|
||||
let deploySourceWorkspace = $derived(mergeIntoParent ? currentWorkspaceId : parentWorkspaceId)
|
||||
|
||||
@@ -1694,6 +1697,10 @@
|
||||
kind={diff.kind}
|
||||
canPreserve={canPreserveOnBehalfOf}
|
||||
customValue={customOnBehalfOf[key]?.permissionedAs}
|
||||
folderDefault={canPreserveOnBehalfOf &&
|
||||
!(mergeIntoParent ? diff.exists_in_source : diff.exists_in_fork)
|
||||
? targetFolderDefault(deployTargetWorkspace, diff.path)
|
||||
: undefined}
|
||||
/>
|
||||
{/if}
|
||||
{#if diff.kind === 'raw_app'}
|
||||
|
||||
@@ -48,6 +48,7 @@
|
||||
type OnBehalfOfChoice,
|
||||
type OnBehalfOfDetails
|
||||
} from './OnBehalfOfSelector.svelte'
|
||||
import { createFolderDefaultLookup } from './useFolderDefaultPermissionedAs.svelte'
|
||||
import ParentWorkspaceProtectionAlert from './ParentWorkspaceProtectionAlert.svelte'
|
||||
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
|
||||
|
||||
@@ -104,6 +105,8 @@
|
||||
let onBehalfOfChoice = $state<Record<string, OnBehalfOfChoice>>({})
|
||||
let customOnBehalfOf = $state<Record<string, OnBehalfOfDetails>>({})
|
||||
let canPreserveOnBehalfOf = $state(false)
|
||||
// An item new in the target takes the target folder's rule unless the deploy names someone.
|
||||
const targetFolderDefault = createFolderDefaultLookup()
|
||||
/** Who the deploy acts as in the target: on a remote instance, the remote token's user. */
|
||||
let deployerEmail = $state<string | undefined>(undefined)
|
||||
|
||||
@@ -648,6 +651,9 @@
|
||||
kind={item.kind}
|
||||
canPreserve={canPreserveOnBehalfOf}
|
||||
customValue={customOnBehalfOf[statusPath]?.permissionedAs}
|
||||
folderDefault={canPreserveOnBehalfOf && exists === false
|
||||
? targetFolderDefault(workspaceToDeployTo!, item.path)
|
||||
: undefined}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
|
||||
@@ -160,7 +160,9 @@
|
||||
onSelect('target')
|
||||
} else if (folderDefault && users.length > 0) {
|
||||
const username = folderDefault.startsWith('u/') ? folderDefault.slice(2) : folderDefault
|
||||
const email = users.find((u) => u.username === username)?.email ?? folderDefault
|
||||
// A group, or a user this list lacks, has no address to send: an empty one names nobody,
|
||||
// so the server derives it from the principal rather than refusing a mismatched pair.
|
||||
const email = users.find((u) => u.username === username)?.email ?? ''
|
||||
onSelect('custom', { email, permissionedAs: folderDefault })
|
||||
}
|
||||
})
|
||||
|
||||
@@ -278,7 +278,7 @@
|
||||
let originalOnBehalfOfEmail = $derived(savedScript?.on_behalf_of_email)
|
||||
let originalOnBehalfOfPermissionedAs = $derived(savedScript?.on_behalf_of)
|
||||
let onBehalfOfChoice: OnBehalfOfChoice = $state(undefined)
|
||||
let customOnBehalfOfEmail: string = $state('')
|
||||
let customOnBehalfOf: string = $state('')
|
||||
let myPermissionedAs = $derived($userStore?.username ? `u/${$userStore.username}` : undefined)
|
||||
// The rule applies on a script's first deploy only.
|
||||
const folderDefault = useFolderDefaultRunAs(
|
||||
@@ -2173,22 +2173,22 @@
|
||||
if (choice === 'me') {
|
||||
script.on_behalf_of_email = $userStore?.email
|
||||
script.on_behalf_of = myPermissionedAs
|
||||
customOnBehalfOfEmail = ''
|
||||
customOnBehalfOf = ''
|
||||
} else if (choice === 'target') {
|
||||
// Keep the saved pair. A script that has no recorded principal yet
|
||||
// sends the email alone and the backend derives one from it.
|
||||
script.on_behalf_of_email = originalOnBehalfOfEmail
|
||||
script.on_behalf_of = originalOnBehalfOfPermissionedAs
|
||||
customOnBehalfOfEmail = ''
|
||||
customOnBehalfOf = ''
|
||||
} else if (choice === 'custom' && details) {
|
||||
script.on_behalf_of_email = details.email
|
||||
script.on_behalf_of = details.permissionedAs
|
||||
customOnBehalfOfEmail = details.email
|
||||
customOnBehalfOf = details.permissionedAs
|
||||
}
|
||||
}}
|
||||
kind="script"
|
||||
{canPreserve}
|
||||
customValue={customOnBehalfOfEmail}
|
||||
customValue={customOnBehalfOf}
|
||||
isDeployment={false}
|
||||
folderDefault={folderDefault.value}
|
||||
/>
|
||||
|
||||
@@ -156,7 +156,7 @@
|
||||
let savedOnBehalfOfEmail = $derived(savedApp?.policy?.on_behalf_of_email)
|
||||
let savedOnBehalfOf = $derived(savedApp?.policy?.on_behalf_of)
|
||||
let onBehalfOfChoice: OnBehalfOfChoice = $state(undefined)
|
||||
let customOnBehalfOfEmail: string = $state('')
|
||||
let customOnBehalfOf: string = $state('')
|
||||
let myOnBehalfOf = $derived(actingUser?.username ? `u/${actingUser.username}` : undefined)
|
||||
// A new app starts on the folder rule its path matches, or on the deployer, and deploys
|
||||
// what is shown: naming nobody would let the server apply a rule this picker did not see.
|
||||
@@ -172,7 +172,7 @@
|
||||
if (onBehalfOfChoice !== undefined && !defaultChosen) return
|
||||
defaultChosen = true
|
||||
onBehalfOfChoice = rule ? 'custom' : 'me'
|
||||
customOnBehalfOfEmail = rule ?? ''
|
||||
customOnBehalfOf = rule ?? ''
|
||||
policy.on_behalf_of = rule ?? myOnBehalfOf
|
||||
policy.on_behalf_of_email = rule ? undefined : $userStore?.email
|
||||
})
|
||||
@@ -357,20 +357,20 @@
|
||||
if (choice === 'me') {
|
||||
policy.on_behalf_of_email = $userStore?.email
|
||||
policy.on_behalf_of = `u/${$userStore?.username}`
|
||||
customOnBehalfOfEmail = ''
|
||||
customOnBehalfOf = ''
|
||||
} else if (choice === 'target') {
|
||||
policy.on_behalf_of_email = savedOnBehalfOfEmail
|
||||
policy.on_behalf_of = savedOnBehalfOf
|
||||
customOnBehalfOfEmail = ''
|
||||
customOnBehalfOf = ''
|
||||
} else if (choice === 'custom' && details) {
|
||||
policy.on_behalf_of_email = details.email
|
||||
policy.on_behalf_of = details.permissionedAs
|
||||
customOnBehalfOfEmail = details.email
|
||||
customOnBehalfOf = details.permissionedAs
|
||||
}
|
||||
}}
|
||||
kind="app"
|
||||
{canPreserve}
|
||||
customValue={customOnBehalfOfEmail}
|
||||
customValue={customOnBehalfOf}
|
||||
isDeployment={false}
|
||||
myPermissionedAs={myOnBehalfOf}
|
||||
readOnlyWithoutPreserve
|
||||
|
||||
@@ -66,7 +66,7 @@
|
||||
let isDeployer = $derived(actingUser?.groups?.includes(WM_DEPLOYERS_GROUP) ?? false)
|
||||
let canPreserve = $derived(!!actingUser?.is_admin || !!actingUser?.is_super_admin || isDeployer)
|
||||
let onBehalfOfChoice: OnBehalfOfChoice = $state(undefined)
|
||||
let customOnBehalfOfEmail: string = $state('')
|
||||
let customOnBehalfOf: string = $state('')
|
||||
let myPermissionedAs = $derived($userStore?.username ? `u/${$userStore.username}` : undefined)
|
||||
// The rule applies on a flow's create only.
|
||||
const folderDefault = useFolderDefaultRunAs(
|
||||
@@ -513,22 +513,22 @@
|
||||
if (choice === 'me') {
|
||||
flowStore.val.on_behalf_of_email = $userStore?.email
|
||||
flowStore.val.on_behalf_of = myPermissionedAs
|
||||
customOnBehalfOfEmail = ''
|
||||
customOnBehalfOf = ''
|
||||
} else if (choice === 'target') {
|
||||
// Keep the saved pair. A flow that has no recorded principal yet
|
||||
// sends the email alone and the backend derives one from it.
|
||||
flowStore.val.on_behalf_of_email = $savedOnBehalfOfEmail
|
||||
flowStore.val.on_behalf_of = $savedOnBehalfOfPermissionedAs
|
||||
customOnBehalfOfEmail = ''
|
||||
customOnBehalfOf = ''
|
||||
} else if (choice === 'custom' && details) {
|
||||
flowStore.val.on_behalf_of_email = details.email
|
||||
flowStore.val.on_behalf_of = details.permissionedAs
|
||||
customOnBehalfOfEmail = details.email
|
||||
customOnBehalfOf = details.permissionedAs
|
||||
}
|
||||
}}
|
||||
kind="flow"
|
||||
{canPreserve}
|
||||
customValue={customOnBehalfOfEmail}
|
||||
customValue={customOnBehalfOf}
|
||||
isDeployment={false}
|
||||
folderDefault={folderDefault.value}
|
||||
/>
|
||||
|
||||
@@ -1,8 +1,25 @@
|
||||
import { FolderService } from '$lib/gen'
|
||||
import { Minimatch } from 'minimatch'
|
||||
import { resource } from 'runed'
|
||||
import { untrack } from 'svelte'
|
||||
import { workspaceStore, userStore } from '$lib/stores'
|
||||
import { folderRuleGlobMatches } from '$lib/utils/folderRuleGlob'
|
||||
|
||||
/** The folder rule a create at `path` takes on the server, for a caller it applies to. */
|
||||
export async function resolveFolderDefaultPermissionedAs(
|
||||
workspace: string,
|
||||
path: string
|
||||
): Promise<string | undefined> {
|
||||
const m = path.match(/^f\/([^/]+)\/(.+)$/)
|
||||
if (!m) return undefined
|
||||
try {
|
||||
const folder = await FolderService.getFolder({ workspace, name: m[1] })
|
||||
return (folder.default_permissioned_as ?? []).find((rule) =>
|
||||
folderRuleGlobMatches(rule.path_glob, m[2])
|
||||
)?.permissioned_as
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the folder's `default_permissioned_as` rule that matches a given item path.
|
||||
@@ -37,29 +54,8 @@ export function useFolderDefaultPermissionedAs(
|
||||
async ({ path, workspace, user }) => {
|
||||
const canPreserve =
|
||||
user?.is_admin || user?.is_super_admin || (user?.groups ?? []).includes('wm_deployers')
|
||||
if (!canPreserve || !workspace || !path?.startsWith('f/')) {
|
||||
return undefined
|
||||
}
|
||||
const parts = path.split('/')
|
||||
if (parts.length < 3) return undefined
|
||||
const folderName = parts[1]
|
||||
const relative = path.slice(`f/${folderName}/`.length)
|
||||
if (!relative) return undefined
|
||||
|
||||
try {
|
||||
const folder = await FolderService.getFolder({ workspace, name: folderName })
|
||||
const rules = folder.default_permissioned_as ?? []
|
||||
const match = rules.find((rule) => {
|
||||
try {
|
||||
return new Minimatch(rule.path_glob).match(relative)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
return match?.permissioned_as
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
if (!canPreserve || !workspace || !path) return undefined
|
||||
return resolveFolderDefaultPermissionedAs(workspace, path)
|
||||
}
|
||||
)
|
||||
|
||||
@@ -90,6 +86,8 @@ export function useFolderDefaultRunAs(
|
||||
const folderDefault = useFolderDefaultPermissionedAs(newPathGetter, wsGetter)
|
||||
let seeded: string | undefined = undefined
|
||||
$effect(() => {
|
||||
// Creation ending (the first deploy) is not the path leaving the rule: keep the identity.
|
||||
if (newPathGetter() === undefined || folderDefault.loading) return
|
||||
const rule = folderDefault.value
|
||||
untrack(() => {
|
||||
if (rule === seeded) return
|
||||
@@ -105,3 +103,20 @@ export function useFolderDefaultRunAs(
|
||||
})
|
||||
return folderDefault
|
||||
}
|
||||
|
||||
/**
|
||||
* Folder rules a deploy into another workspace meets, looked up once per item on first read.
|
||||
* Only an item new in that workspace takes one, so callers ask only for those.
|
||||
*/
|
||||
export function createFolderDefaultLookup() {
|
||||
const values = $state<Record<string, string | undefined>>({})
|
||||
const requested = new Set<string>()
|
||||
return (workspace: string, path: string): string | undefined => {
|
||||
const key = `${workspace}:${path}`
|
||||
if (!requested.has(key)) {
|
||||
requested.add(key)
|
||||
resolveFolderDefaultPermissionedAs(workspace, path).then((v) => (values[key] = v))
|
||||
}
|
||||
return values[key]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { folderRuleGlobMatches } from './folderRuleGlob'
|
||||
|
||||
// Expected matches are what `globset::Glob::new(glob).compile_matcher()` answers on the server.
|
||||
const PATHS = ['x', 'jobs/a', 'jobs/a/b', 'a/b', 'a/x/b', 'a/c', 'abc', 'foo/z', 'bar/z/q', 'baz/z']
|
||||
const CASES: [string, string[]][] = [
|
||||
['**', PATHS],
|
||||
['*', PATHS],
|
||||
['**/', PATHS],
|
||||
['jobs/*', ['jobs/a', 'jobs/a/b']],
|
||||
['a/**/b', ['a/b', 'a/x/b']],
|
||||
['**/x', ['x']],
|
||||
['a?c', ['a/c', 'abc']],
|
||||
['[!ab]*', ['x', 'jobs/a', 'jobs/a/b', 'foo/z']],
|
||||
['{foo,bar}/*', ['foo/z', 'bar/z/q']],
|
||||
['[unclosed', []]
|
||||
]
|
||||
|
||||
describe('folderRuleGlobMatches', () => {
|
||||
it.each(CASES)('%s matches what the server matches', (glob, expected) => {
|
||||
expect(PATHS.filter((p) => folderRuleGlobMatches(glob, p))).toEqual(expected)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Whether a folder `default_permissioned_as` glob matches a path relative to its folder, with
|
||||
* the semantics the server applies (`globset::Glob` defaults): `*` and `?` also match `/`,
|
||||
* `**` spans any depth, `{a,b}` alternates, `[!x]` negates, and an invalid glob matches nothing.
|
||||
* The editors send the rule they preview, so a matcher that disagrees with the server stores
|
||||
* an identity other than the one the folder rule would have given.
|
||||
*/
|
||||
export function folderRuleGlobMatches(glob: string, relativePath: string): boolean {
|
||||
const source = globToRegexSource(glob)
|
||||
return source !== undefined && new RegExp(`^${source}$`, 's').test(relativePath)
|
||||
}
|
||||
|
||||
function globToRegexSource(glob: string): string | undefined {
|
||||
let re = ''
|
||||
for (let i = 0; i < glob.length; i++) {
|
||||
const c = glob[i]
|
||||
if (c === '*') {
|
||||
if (glob[i + 1] !== '*') {
|
||||
re += '.*'
|
||||
continue
|
||||
}
|
||||
const atSegmentStart = i === 0 || glob[i - 1] === '/'
|
||||
i++
|
||||
if (atSegmentStart && glob[i + 1] === '/' && i + 2 < glob.length) {
|
||||
re += '(?:.*/)?'
|
||||
i++
|
||||
} else {
|
||||
re += '.*'
|
||||
if (glob[i + 1] === '/') i++
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '.'
|
||||
} else if (c === '[') {
|
||||
const end = glob.indexOf(']', i + 2)
|
||||
if (end < 0) return undefined
|
||||
let body = glob.slice(i + 1, end).replace(/[\\^]/g, '\\$&')
|
||||
if (body.startsWith('!')) body = '^' + body.slice(1)
|
||||
re += `[${body}]`
|
||||
i = end
|
||||
} else if (c === '{') {
|
||||
const end = glob.indexOf('}', i)
|
||||
if (end < 0) return undefined
|
||||
const alternatives = glob
|
||||
.slice(i + 1, end)
|
||||
.split(',')
|
||||
.map(globToRegexSource)
|
||||
if (alternatives.some((a) => a === undefined)) return undefined
|
||||
re += `(?:${alternatives.join('|')})`
|
||||
i = end
|
||||
} else if (c === '\\' && i + 1 < glob.length) {
|
||||
re += escapeRegex(glob[++i])
|
||||
} else {
|
||||
re += escapeRegex(c)
|
||||
}
|
||||
}
|
||||
return re
|
||||
}
|
||||
|
||||
function escapeRegex(c: string): string {
|
||||
return c.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')
|
||||
}
|
||||
Reference in New Issue
Block a user