按当前 dev 重写贡献者 PR #264 的两项核心意图: 1. 面包屑折叠(VSCode "compact folders"):host 给「内容恰为一个有效 子项」的目录行标记 `compact`,client 把单目录链折叠成一行 `a/b/c` 并整链展开/折叠。 2. `explorerExclude`(VS Code `files.exclude` 风格的 glob 子集):匹配 条目从文件树与文件名搜索中彻底移除;树与搜索共用同一份 host 侧编译 好的 matcher,两个界面永不失配。 为什么按 dev 现有结构重写而不是机械解冲突——证据卡逐条点名的 dev 侧变化: - **客户端树已换成 DirRow 记忆化组件 + loadLevels/api.fsTrees 批量路由**。 PR 改的是旧的 `expanded.includes(...)` 内联目录行与单路径 `api.fsTree`, 该上下文在 dev 已不存在。折叠因此接在 renderLevel/visibleRows 的链上, 并新增「每级缓存修订一次」的链缓存:DirRow 按 prop 身份 memo,每次渲染 新建数组会让选择/悬停把每个目录行都重渲。 - **`api.fsTree(scope, path, signal?)` 的第三位已经是 AbortSignal**,PR 的 `api.fsTree(scope, dir, exclude)` 会把数组当 signal。exclude 统一排在 signal 之前(`fsTree`/`fsTrees`/`fsSearch` 三处一致)。 - **dev 的 `listDirectory` 有 1.5s TTL 缓存,PR 是直接读盘**。照搬会让不同 排除集共用一份缓存(改完排除列表仍读到旧行),而 pref 变更没有可搭的 失效钩子。故把模式集的身份并入 cacheKey(新增 `ExcludeMatcher.key`,含 锚点 root 与大小写折叠语义):同列表命中缓存,改列表即换键。 - **文件树的真实入口是批量路由 `fs.trees`**(挂载/展开一次 POST),PR 只 改了 `fs.tree`/`fs.search` 两处——不接批量路由等于 exclude 不生效。 - PR body 声称移除 `explorerShowHidden`,但净 diff 对它零命中、dev 与 PR 合并基也都没有该键,属失效声明,不做产品取舍。 复用的部分(与 dev 无耦合):`src/exclude-patterns.ts` 与 `src/client/file-tree-compact.ts` 两个纯逻辑模块逐字取用(前者仅新增缓存 身份 `ExcludeMatcher.key`)。设置 UI 沿用 PR 的声明式 `patterns` 行类型 (chips + 删除钮 + 常驻添加输入框,原子提交整表),5 个新词条按仓库规则 同步全部 21 份词典;`src/client/service.ts` 的能力清单新增 `settingPatterns` 并同步 docs/external-plugin-guide.md。 门禁:pnpm typecheck 0;pnpm exec vitest run --maxWorkers=3 全绿 (165 files / 1847 passed / 13 skipped);npx eslint 45 个改动文件 0; 新增与改动的 spec 单跑 154 passed;pnpm build 0。 Refs #264
164 lines
6.8 KiB
TypeScript
164 lines
6.8 KiB
TypeScript
/**
|
|
* Glob-style exclude patterns for the explorer tree and name search — the
|
|
* VS Code `files.exclude` lineage. One compiled matcher serves BOTH host
|
|
* consumption points (the `fs.tree` level listing and the `fs.search` walk)
|
|
* so a pattern can never disagree between the two surfaces.
|
|
*
|
|
* Pattern grammar (a deliberate subset of VS Code's globs):
|
|
* - `name` matches that base NAME at any depth (`Thumbs.db`);
|
|
* - `dir/name` path-anchored at the session cwd (`build/out`);
|
|
* - doublestar-slash head (`**` + `/name`) matches at any depth (the head strips away);
|
|
* - `*` / `?` wildcards within one segment; `**` spans segments.
|
|
* Matching is case-sensitive on POSIX and case-insensitive on Windows (the
|
|
* filesystem's own notion). Invalid shapes (empty, overlong, over the count
|
|
* cap) are dropped silently — a malformed pattern must never break the tree.
|
|
*/
|
|
import { relative, sep } from 'node:path'
|
|
|
|
/** Hard cap on how many patterns one request may carry (extras dropped). */
|
|
export const EXCLUDE_PATTERN_LIMIT = 64
|
|
/** Hard cap on one pattern's length (longer ones dropped). */
|
|
export const EXCLUDE_PATTERN_MAX_LENGTH = 256
|
|
|
|
/** One entry probe: the entry's absolute path and its base name. */
|
|
export type ExcludeTest = (entryPath: string, name: string) => boolean
|
|
|
|
/**
|
|
* A compiled probe plus the canonical identity of the pattern set it was
|
|
* built from. The identity exists so a caller can key a cache on the
|
|
* FILTERING, not just on the directory: the host's level cache stores rows
|
|
* already filtered, so serving a listing compiled from one pattern list to a
|
|
* request carrying another would keep showing rows the user just excluded
|
|
* (and hide rows just un-excluded) for the rest of the TTL. Two calls that
|
|
* normalized to the same patterns share a key, so the cache still absorbs
|
|
* repeat listings of an unchanged list.
|
|
*/
|
|
export interface ExcludeMatcher extends ExcludeTest {
|
|
/** Canonical identity of the compiled pattern set ('' when nothing valid). */
|
|
readonly key: string
|
|
}
|
|
|
|
/** One compiled pattern and the surface it claims. */
|
|
interface CompiledPattern {
|
|
/** 'name' tests the base name anywhere; 'path' tests the cwd-relative
|
|
* path anchored at the root; 'suffix' (a doublestar-slash head shape) tests
|
|
* the name
|
|
* OR any trailing segment run of the relative path. */
|
|
kind: 'name' | 'path' | 'suffix'
|
|
regex: RegExp
|
|
}
|
|
|
|
/**
|
|
* Normalize one raw pattern (accepts unknown wire values): trim, unify
|
|
* separators, drop the doublestar-slash head (remembered as a suffix kind) and the
|
|
* `./` and trailing-/ decorations. Returns undefined for empty/invalid input.
|
|
*/
|
|
function normalizePattern(raw: unknown): { kind: CompiledPattern['kind']; body: string } | undefined {
|
|
if (typeof raw !== 'string') return undefined
|
|
let pattern = raw.trim().replace(/\\/g, '/')
|
|
if (pattern.length > EXCLUDE_PATTERN_MAX_LENGTH) return undefined
|
|
while (pattern.startsWith('./')) pattern = pattern.slice(2)
|
|
while (pattern.startsWith('/')) pattern = pattern.slice(1)
|
|
while (pattern.endsWith('/')) pattern = pattern.slice(0, -1)
|
|
let kind: CompiledPattern['kind'] = 'name'
|
|
if (pattern.startsWith('**/')) {
|
|
kind = 'suffix'
|
|
pattern = pattern.slice(3)
|
|
}
|
|
if (pattern === '' || pattern === '**') {
|
|
// A bare `**` (or one that stripped to nothing) would swallow the whole
|
|
// tree — refuse it instead of hiding everything.
|
|
return undefined
|
|
}
|
|
if (kind === 'name' && pattern.includes('/')) kind = 'path'
|
|
return { kind, body: pattern }
|
|
}
|
|
|
|
/** Compile one normalized glob body to an anchored RegExp. */
|
|
function globToRegExp(body: string, insensitive: boolean): RegExp {
|
|
let out = ''
|
|
for (let i = 0; i < body.length; i += 1) {
|
|
const char = body[i]!
|
|
if (char === '*') {
|
|
if (body[i + 1] === '*') {
|
|
out += '.*'
|
|
i += 1
|
|
} else {
|
|
out += '[^/]*'
|
|
}
|
|
continue
|
|
}
|
|
if (char === '?') {
|
|
out += '[^/]'
|
|
continue
|
|
}
|
|
out += char.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
}
|
|
return new RegExp(`^${out}$`, insensitive ? 'i' : undefined)
|
|
}
|
|
|
|
/** The cwd-relative '/' path of `entryPath` (undefined when outside `root`). */
|
|
function relativeToRoot(root: string, entryPath: string): string | undefined {
|
|
const rel = relative(root, entryPath).split(sep).join('/')
|
|
return rel.startsWith('..') ? undefined : rel
|
|
}
|
|
|
|
/**
|
|
* Compile the wire patterns into one entry probe.
|
|
* @param raw - the request payload's `exclude` field (anything; validated).
|
|
* @param root - the session cwd the path-anchored patterns resolve against.
|
|
* @param platform - case-folding semantics (`'win32'` matches insensitively).
|
|
* @returns the probe (with its {@link ExcludeMatcher.key}), or undefined when
|
|
* nothing valid was declared (callers skip filtering entirely then — the
|
|
* no-pattern fast path).
|
|
*/
|
|
export function compileExcludePatterns(
|
|
raw: unknown,
|
|
root: string,
|
|
platform: NodeJS.Platform | 'posix' = process.platform,
|
|
): ExcludeMatcher | undefined {
|
|
if (!Array.isArray(raw)) return undefined
|
|
const compiled: CompiledPattern[] = []
|
|
for (const item of raw) {
|
|
if (compiled.length >= EXCLUDE_PATTERN_LIMIT) break
|
|
const normalized = normalizePattern(item)
|
|
if (normalized === undefined) continue
|
|
compiled.push({ kind: normalized.kind, regex: globToRegExp(normalized.body, platform === 'win32') })
|
|
}
|
|
if (compiled.length === 0) return undefined
|
|
const needsRel = compiled.some(pattern => pattern.kind !== 'name')
|
|
const probe = (entryPath: string, name: string): boolean => {
|
|
let rel: string | undefined
|
|
for (const pattern of compiled) {
|
|
if (pattern.kind === 'name') {
|
|
if (pattern.regex.test(name)) return true
|
|
continue
|
|
}
|
|
if (rel === undefined) {
|
|
if (!needsRel) continue
|
|
rel = relativeToRoot(root, entryPath) ?? ''
|
|
}
|
|
if (pattern.kind === 'path') {
|
|
if (rel !== '' && pattern.regex.test(rel)) return true
|
|
continue
|
|
}
|
|
// Suffix kind: the name itself or any trailing segment run of rel.
|
|
if (pattern.regex.test(name)) return true
|
|
if (rel !== '') {
|
|
const segments = rel.split('/')
|
|
for (let start = 0; start < segments.length - 1; start += 1) {
|
|
if (pattern.regex.test(segments.slice(start).join('/'))) return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
// The identity covers everything the probe reads: the compiled kinds and
|
|
// their regexes (case-folding included) plus the root the path-anchored
|
|
// kinds resolve against — two sessions with the same patterns but different
|
|
// cwds match a given directory differently, so they must not share a cache
|
|
// entry. NUL joins because no pattern body can contain one.
|
|
const key = `${root}\0${compiled.map(pattern => `${pattern.kind}:${pattern.regex.source}:${pattern.regex.flags}`).join('\0')}`
|
|
return Object.assign(probe, { key })
|
|
}
|