(pattern: string, caseSensitive: boolean)
| 184 | * @internal |
| 185 | */ |
| 186 | export function globPatternToRegex(pattern: string, caseSensitive: boolean): RegExp { |
| 187 | let regex = '^'; |
| 188 | for (let i = 0; i < pattern.length; i++) { |
| 189 | const ch = pattern[i]; |
| 190 | if (ch === undefined) break; |
| 191 | switch (ch) { |
| 192 | case '*': |
| 193 | regex += '[^/]*'; |
| 194 | break; |
| 195 | case '?': |
| 196 | regex += '[^/]'; |
| 197 | break; |
| 198 | case '[': { |
| 199 | const end = pattern.indexOf(']', i + 1); |
| 200 | if (end === -1) { |
| 201 | regex += '\\['; |
| 202 | } else { |
| 203 | // Glob character classes only use `!` for negation. A literal |
| 204 | // leading `^` must remain literal even though JS regex char |
| 205 | // classes treat it as negation in the first position. |
| 206 | let charClass = pattern.slice(i + 1, end); |
| 207 | // Escape backslashes inside the class so a trailing backslash |
| 208 | // does not accidentally escape the closing `]`. |
| 209 | charClass = charClass.replace(/\\/g, '\\\\'); |
| 210 | if (charClass.startsWith('!')) { |
| 211 | charClass = '^' + charClass.slice(1); |
| 212 | } else if (charClass.startsWith('^')) { |
| 213 | charClass = '\\' + charClass; |
| 214 | } |
| 215 | regex += '[' + charClass + ']'; |
| 216 | i = end; |
| 217 | } |
| 218 | break; |
| 219 | } |
| 220 | case '\\': { |
| 221 | if (i + 1 < pattern.length) { |
| 222 | const next = pattern.charAt(i + 1); |
| 223 | regex += next.replaceAll(/[{}()+.\\[\]^$|]/g, '\\$&'); |
| 224 | // Advance past the escaped character so it is not processed |
| 225 | // again as a regex metacharacter. match literally. |
| 226 | i++; |
| 227 | } else { |
| 228 | regex += '\\\\'; |
| 229 | } |
| 230 | break; |
| 231 | } |
| 232 | default: |
| 233 | regex += ch.replaceAll(/[{}()+.\\[\]^$|]/g, '\\$&'); |
| 234 | } |
| 235 | } |
| 236 | regex += '$'; |
| 237 | return new RegExp(regex, caseSensitive ? '' : 'i'); |
| 238 | } |
| 239 | |
| 240 | /** |
| 241 | * A Readable wrapper that preserves source backpressure while still allowing |
no outgoing calls
no test coverage detected