• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2024 - 2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16export class GlobMatch {
17    private regexps: string[] = [];
18
19    constructor(globPattern: string[]) {
20        this.regexps = globPattern.map(pattern => this.globToRegexp(pattern));
21    }
22
23    matchGlob(path: string): boolean {
24        path = path.replace(/\\/g, '/');
25        return this.regexps.some(regexp => new RegExp(regexp).test(path));
26    }
27
28    private globToRegexp(glob: string): string {
29        glob = glob.replace(/\\/g, '/').replace(/\/+/g, '/');
30        const specialChars = new Set(['.', '+', '*', '?', '[', '^', ']', '(', ')', '{', '}', '|']);
31        let regexp = '';
32        let isStar = false;
33        for (let i = 0; i < glob.length; i++) {
34            const char = glob[i];
35            if (char === '*') {
36                if (!isStar) {
37                    regexp += '.*'; // 匹配任意字符序列,包括空字符串。
38                }
39                isStar = true;
40                continue;
41            } else if (char === '?') {
42                regexp += '.'; // 匹配任意单个字符。
43            } else if (specialChars.has(char)) {
44                regexp += `\\${char}`; // 转义特殊字符。
45            } else {
46                regexp += char;
47            }
48            isStar = false;
49        }
50        // 防止配置的是'.c', 匹配到了'.cpp'
51        if (regexp.match('.*\\.[a-zA-Z]+$')) {
52            regexp = `${regexp}$`;
53        }
54        return regexp;
55    }
56}