| 1 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 2 |
# Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]> |
| 3 |
|
| 4 |
'''This module contains functions for transforming bash glob patterns.''' |
| 5 |
|
| 6 |
|
| 7 |
from .string_stream import StringStream |
| 8 |
|
| 9 |
|
| 10 |
class PatternBase: |
| 11 |
'''Base class for glob patterns.''' |
| 12 |
|
| 13 |
def to_regex(self): |
| 14 |
'''Make a regular expression.''' |
| 15 |
raise NotImplementedError |
| 16 |
|
| 17 |
def to_zsh_glob(self): |
| 18 |
'''Make a Zsh glob.''' |
| 19 |
raise NotImplementedError |
| 20 |
|
| 21 |
|
| 22 |
class Literal(PatternBase): |
| 23 |
'''Holds a literal string.''' |
| 24 |
|
| 25 |
REGEX_ESCAPE_CHARS = '.?*+|{}[]()' |
| 26 |
|
| 27 |
def __init__(self, string): |
| 28 |
self.string = string |
| 29 |
|
| 30 |
def __str__(self): |
| 31 |
return self.string |
| 32 |
|
| 33 |
def __repr__(self): |
| 34 |
return self.string |
| 35 |
|
| 36 |
def to_regex(self): |
| 37 |
string = self.string |
| 38 |
|
| 39 |
for c in Literal.REGEX_ESCAPE_CHARS: |
| 40 |
string = string.replace(c, f'\\{c}') |
| 41 |
|
| 42 |
return string |
| 43 |
|
| 44 |
def to_zsh_glob(self): |
| 45 |
string = '' |
| 46 |
|
| 47 |
for c in self.string: |
| 48 |
if c in ('[', ']', '?', '*', '"', ' ', '\\'): |
| 49 |
string += f"'{c}'" |
| 50 |
elif c == "'": |
| 51 |
string += f'"{c}"' |
| 52 |
else: |
| 53 |
string += c |
| 54 |
|
| 55 |
return string |
| 56 |
|
| 57 |
|
| 58 |
class Star(PatternBase): |
| 59 |
'''Represents a star glob (*).''' |
| 60 |
|
| 61 |
def to_regex(self): |
| 62 |
return '.*' |
| 63 |
|
| 64 |
def to_zsh_glob(self): |
| 65 |
return '*' |
| 66 |
|
| 67 |
|
| 68 |
class Question(PatternBase): |
| 69 |
'''Represents a question glob (?).''' |
| 70 |
|
| 71 |
def to_regex(self): |
| 72 |
return '.' |
| 73 |
|
| 74 |
def to_zsh_glob(self): |
| 75 |
return '?' |
| 76 |
|
| 77 |
|
| 78 |
class CharClass(PatternBase): |
| 79 |
'''Represents a character class.''' |
| 80 |
|
| 81 |
REGEX_ESCAPE_CHARS = r'^\.[]' |
| 82 |
|
| 83 |
def __init__(self, chars, negated): |
| 84 |
self.chars = chars |
| 85 |
self.negated = negated |
| 86 |
|
| 87 |
def to_regex(self): |
| 88 |
chars = self.chars |
| 89 |
|
| 90 |
for c in CharClass.REGEX_ESCAPE_CHARS: |
| 91 |
chars = chars.replace(c, f'\\{c}') |
| 92 |
|
| 93 |
if self.negated: |
| 94 |
return f'[^{chars}]' |
| 95 |
|
| 96 |
return f'[{chars}]' |
| 97 |
|
| 98 |
def to_zsh_glob(self): |
| 99 |
chars = '' |
| 100 |
|
| 101 |
for c in self.chars: |
| 102 |
if c in ('[', ']', '!'): |
| 103 |
chars += f"'{c}'" |
| 104 |
else: |
| 105 |
chars += c |
| 106 |
|
| 107 |
if self.negated: |
| 108 |
return f'[!{chars}]' |
| 109 |
|
| 110 |
return f'[{chars}]' |
| 111 |
|
| 112 |
|
| 113 |
class ExtGlob(PatternBase): |
| 114 |
'''Holds an extglob: @(), *(), ?(), +(), !().''' |
| 115 |
|
| 116 |
def __init__(self, type_, alternatives): |
| 117 |
self.type = type_ |
| 118 |
self.alternatives = alternatives |
| 119 |
|
| 120 |
def to_regex(self): |
| 121 |
r = [] |
| 122 |
|
| 123 |
for alternative in self.alternatives: |
| 124 |
r.append(alternative.to_regex()) |
| 125 |
|
| 126 |
p = '(%s)' % '|'.join(r) |
| 127 |
|
| 128 |
if self.type == '@': |
| 129 |
return p |
| 130 |
|
| 131 |
if self.type == '*': |
| 132 |
return p + '*' |
| 133 |
|
| 134 |
if self.type == '+': |
| 135 |
return p + '+' |
| 136 |
|
| 137 |
if self.type == '?': |
| 138 |
return p + '?' |
| 139 |
|
| 140 |
if self.type == '!': |
| 141 |
raise ValueError('Negated glob !(...) not supported in regex') |
| 142 |
|
| 143 |
raise AssertionError("Not reached") |
| 144 |
|
| 145 |
def to_zsh_glob(self): |
| 146 |
r = [] |
| 147 |
|
| 148 |
for alternative in self.alternatives: |
| 149 |
r.append(alternative.to_zsh_glob()) |
| 150 |
|
| 151 |
p = '(%s)' % '|'.join(r) |
| 152 |
|
| 153 |
if self.type == '@': |
| 154 |
return p |
| 155 |
|
| 156 |
if self.type in ('*', '+', '?', '!'): |
| 157 |
raise ValueError(f'Extended glob of form {self.type}(...) not supported in zsh glob') |
| 158 |
|
| 159 |
raise AssertionError("Not reached") |
| 160 |
|
| 161 |
|
| 162 |
class PatternList(PatternBase): |
| 163 |
'''Holds a list of patterns.''' |
| 164 |
|
| 165 |
def __init__(self): |
| 166 |
self.tokens = [] |
| 167 |
|
| 168 |
def to_regex(self): |
| 169 |
return ''.join(t.to_regex() for t in self.tokens) |
| 170 |
|
| 171 |
def to_zsh_glob(self): |
| 172 |
return ''.join(t.to_zsh_glob() for t in self.tokens) |
| 173 |
|
| 174 |
def append(self, token): |
| 175 |
'''Add a token.''' |
| 176 |
self.tokens.append(token) |
| 177 |
|
| 178 |
|
| 179 |
EXTGLOB_TOKENS = ('@(', '*(', '+(', '?(', '!(', '+(') |
| 180 |
EXTGLOB_TOKENS_PRE = ('@', '*', '+', '?', '!', '+') |
| 181 |
|
| 182 |
|
| 183 |
class GlobLexer(StringStream): |
| 184 |
'''Class for splitting a pattern into tokens.''' |
| 185 |
|
| 186 |
def __init__(self, pattern): |
| 187 |
super().__init__(pattern) |
| 188 |
self.tokens = [] |
| 189 |
|
| 190 |
def parse(self): |
| 191 |
'''Split string into tokens.''' |
| 192 |
tokens = [] |
| 193 |
|
| 194 |
while True: |
| 195 |
try: |
| 196 |
tokens.append(self._parse_token()) |
| 197 |
except IndexError: |
| 198 |
return tokens |
| 199 |
|
| 200 |
def _parse_token(self): |
| 201 |
c = self.get() |
| 202 |
|
| 203 |
if c in EXTGLOB_TOKENS_PRE and self.peek() == '(': |
| 204 |
return f'{c}{self.get()}' |
| 205 |
|
| 206 |
if c in ('[', ']', ')', '?', '!', '*', '|'): |
| 207 |
return c |
| 208 |
|
| 209 |
if c == '"': |
| 210 |
return Literal(self.parse_shell_double_quote(in_quotes=True)) |
| 211 |
|
| 212 |
if c == "'": |
| 213 |
return Literal(self.parse_shell_single_quote(in_quotes=True)) |
| 214 |
|
| 215 |
literal = c |
| 216 |
while True: |
| 217 |
c = self.peek() |
| 218 |
if c is None: |
| 219 |
break |
| 220 |
if c in EXTGLOB_TOKENS_PRE and self.peek(1) == '(': |
| 221 |
break |
| 222 |
if c in ('*', '?', '[', ']', ')', '|', '"', "'"): |
| 223 |
break |
| 224 |
literal += c |
| 225 |
self.get() |
| 226 |
|
| 227 |
return Literal(literal) |
| 228 |
|
| 229 |
|
| 230 |
class GlobParser: |
| 231 |
'''Parses tokens from GlobLexer.''' |
| 232 |
|
| 233 |
def __init__(self, tokens): |
| 234 |
self.tokens = tokens |
| 235 |
self.i = 0 |
| 236 |
|
| 237 |
def get(self): |
| 238 |
'''Return a token and advance position.''' |
| 239 |
token = self.tokens[self.i] |
| 240 |
self.i += 1 |
| 241 |
return token |
| 242 |
|
| 243 |
def peek(self): |
| 244 |
'''Return current token without advancing the position.''' |
| 245 |
try: |
| 246 |
return self.tokens[self.i] |
| 247 |
except IndexError: |
| 248 |
return None |
| 249 |
|
| 250 |
def have(self): |
| 251 |
'''Return True if there are any tokens left.''' |
| 252 |
return self.i < len(self.tokens) |
| 253 |
|
| 254 |
def parse(self): |
| 255 |
'''Parse tokens and return a PatternList object.''' |
| 256 |
root = PatternList() |
| 257 |
while self.have(): |
| 258 |
root.append(self._parse_token()) |
| 259 |
return root |
| 260 |
|
| 261 |
def _parse_char_class(self): |
| 262 |
chars = '' |
| 263 |
negated = False |
| 264 |
|
| 265 |
try: |
| 266 |
token = self.get() |
| 267 |
except IndexError as e: |
| 268 |
raise ValueError('Unclosed character class') from e |
| 269 |
|
| 270 |
if token == '!': |
| 271 |
negated = True |
| 272 |
elif token == ']': |
| 273 |
raise ValueError('Empty character class') |
| 274 |
else: |
| 275 |
chars += str(token) |
| 276 |
|
| 277 |
while True: |
| 278 |
try: |
| 279 |
token = self.get() |
| 280 |
except IndexError as e: |
| 281 |
raise ValueError('Unclosed character class') from e |
| 282 |
|
| 283 |
if token == ']': |
| 284 |
return CharClass(chars, negated) |
| 285 |
|
| 286 |
chars += str(token) |
| 287 |
|
| 288 |
def _parse_ext_glob(self, token): |
| 289 |
type_ = token[0] |
| 290 |
alternatives = [PatternList()] |
| 291 |
|
| 292 |
while True: |
| 293 |
token = self.peek() |
| 294 |
|
| 295 |
if token == ')': |
| 296 |
self.get() |
| 297 |
return ExtGlob(type_, alternatives) |
| 298 |
|
| 299 |
if token == '|': |
| 300 |
self.get() |
| 301 |
alternatives.append(PatternList()) |
| 302 |
elif token is None: |
| 303 |
raise ValueError('Unclosed extglob') |
| 304 |
else: |
| 305 |
alternatives[-1].append(self._parse_token()) |
| 306 |
|
| 307 |
def _parse_token(self): |
| 308 |
token = self.get() |
| 309 |
|
| 310 |
if token == '[': |
| 311 |
return self._parse_char_class() |
| 312 |
|
| 313 |
if token == '*': |
| 314 |
return Star() |
| 315 |
|
| 316 |
if token == '?': |
| 317 |
return Question() |
| 318 |
|
| 319 |
if token in EXTGLOB_TOKENS: |
| 320 |
return self._parse_ext_glob(token) |
| 321 |
|
| 322 |
return token |
| 323 |
|
| 324 |
|
| 325 |
def bash_glob_to_regex(pattern): |
| 326 |
'''Transform a bash glob to regex.''' |
| 327 |
|
| 328 |
tokens = GlobLexer(pattern).parse() |
| 329 |
tokens = GlobParser(tokens).parse() |
| 330 |
return tokens.to_regex() |
| 331 |
|
| 332 |
|
| 333 |
def bash_glob_to_zsh_glob(pattern): |
| 334 |
'''Transform a bash glob to zsh glob.''' |
| 335 |
|
| 336 |
tokens = GlobLexer(pattern).parse() |
| 337 |
tokens = GlobParser(tokens).parse() |
| 338 |
return tokens.to_zsh_glob() |
| 339 |
|
| 340 |
|
| 341 |
def test(): |
| 342 |
'''Tests.''' |
| 343 |
|
| 344 |
def do_test(num, bash_pattern, expected_regex, expected_zsh_glob): |
| 345 |
'''Do a test case.''' |
| 346 |
|
| 347 |
try: |
| 348 |
regex_result = bash_glob_to_regex(bash_pattern) |
| 349 |
except ValueError: |
| 350 |
regex_result = ValueError |
| 351 |
|
| 352 |
try: |
| 353 |
zsh_glob_result = bash_glob_to_zsh_glob(bash_pattern) |
| 354 |
except ValueError: |
| 355 |
zsh_glob_result = ValueError |
| 356 |
|
| 357 |
if regex_result != expected_regex: |
| 358 |
print('Test %d (regex):' % num) |
| 359 |
print('Having: %s' % regex_result) |
| 360 |
print('Expected: %s' % expected_regex) |
| 361 |
raise AssertionError('Test failed') |
| 362 |
|
| 363 |
if zsh_glob_result != expected_zsh_glob: |
| 364 |
print('Test %d (zsh glob):' % num) |
| 365 |
print('Having: %s' % zsh_glob_result) |
| 366 |
print('Expected: %s' % expected_zsh_glob) |
| 367 |
raise AssertionError('Test failed') |
| 368 |
|
| 369 |
tests = [ |
| 370 |
# Literals |
| 371 |
(0, r'a', r'a', r'a'), |
| 372 |
(1, r'abc', r'abc', r'abc'), |
| 373 |
(3, r'"abc"', r'abc', r'abc'), |
| 374 |
(4, r"'abc'", r'abc', r'abc'), |
| 375 |
(5, r"'a'b'c'", r'abc', r'abc'), |
| 376 |
(6, r'.', r'\.', r'.'), |
| 377 |
(7, r'+', r'\+', r'+'), |
| 378 |
(8, r'@', r'@', r'@'), |
| 379 |
(9, r'"["', r'\[', r"'['"), |
| 380 |
(10, r"'['", r'\[', r"'['"), |
| 381 |
(11, r'"]"', r'\]', r"']'"), |
| 382 |
(12, r"']'", r'\]', r"']'"), |
| 383 |
(13, r"'*'", r'\*', r"'*'"), |
| 384 |
(14, r"'?'", r'\?', r"'?'"), |
| 385 |
|
| 386 |
# Simple globbing |
| 387 |
(15, r'*', r'.*', r'*'), |
| 388 |
(16, r'?', r'.', r'?'), |
| 389 |
(17, r'???', r'...', r'???'), |
| 390 |
|
| 391 |
# Literals + simple globbing |
| 392 |
(18, r'*abc*', r'.*abc.*', r'*abc*'), |
| 393 |
(19, r'*.*', r'.*\..*', r'*.*'), |
| 394 |
(20, r'*+*', r'.*\+.*', r'*+*'), |
| 395 |
|
| 396 |
# Character classes |
| 397 |
(21, r'[abc]', r'[abc]', r'[abc]'), |
| 398 |
(22, r'[.]', r'[\.]', r'[.]'), |
| 399 |
(23, r'[+]', r'[+]', r'[+]'), |
| 400 |
(24, r'[}]', r'[}]', r'[}]'), |
| 401 |
(25, r'[{]', r'[{]', r'[{]'), |
| 402 |
(26, r'[*]', r'[*]', r'[*]'), |
| 403 |
(27, r'[(]', r'[(]', r'[(]'), |
| 404 |
(28, r'[)]', r'[)]', r'[)]'), |
| 405 |
(29, r'["["]', r'[\[]', r"['[']"), |
| 406 |
(30, r'["]"]', r'[\]]', r"[']']"), |
| 407 |
|
| 408 |
# Extglob @ |
| 409 |
(31, r'@(foo)', r'(foo)', r'(foo)'), |
| 410 |
(32, r'@(foo|bar)', r'(foo|bar)', r'(foo|bar)'), |
| 411 |
(33, r'@(|foo)', r'(|foo)', r'(|foo)'), |
| 412 |
|
| 413 |
# Extglob * |
| 414 |
(34, r'*(foo|bar)', r'(foo|bar)*', ValueError), |
| 415 |
(35, r'*(foo)', r'(foo)*', ValueError), |
| 416 |
(36, r'*(|foo)', r'(|foo)*', ValueError), |
| 417 |
|
| 418 |
# Extglob + |
| 419 |
(37, r'+(foo|bar)', r'(foo|bar)+', ValueError), |
| 420 |
(38, r'+(foo)', r'(foo)+', ValueError), |
| 421 |
(39, r'+(|foo)', r'(|foo)+', ValueError), |
| 422 |
|
| 423 |
# Extglob ? |
| 424 |
(40, r'?(foo|bar)', r'(foo|bar)?', ValueError), |
| 425 |
(41, r'?(foo)', r'(foo)?', ValueError), |
| 426 |
(42, r'?(|foo)', r'(|foo)?', ValueError), |
| 427 |
|
| 428 |
# Extglob ! |
| 429 |
(43, r'!(foo|bar)', ValueError, ValueError), |
| 430 |
|
| 431 |
# Nested |
| 432 |
(44, r'@([abc]|foo)', r'([abc]|foo)', r'([abc]|foo)'), |
| 433 |
(45, r'@(@(foo|bar))', r'((foo|bar))', r'((foo|bar))'), |
| 434 |
(46, r'@(@("foo"|bar))', r'((foo|bar))', r'((foo|bar))'), |
| 435 |
(47, r'@(?|bar)', r'(.|bar)', r'(?|bar)'), |
| 436 |
(48, r'@(*baz|bar)', r'(.*baz|bar)', r'(*baz|bar)'), |
| 437 |
|
| 438 |
# Syntax errors |
| 439 |
(70, r'@(foo', ValueError, ValueError), |
| 440 |
(71, r'[abc', ValueError, ValueError), |
| 441 |
(71, r'"abc', ValueError, ValueError), |
| 442 |
(71, r"'abc", ValueError, ValueError), |
| 443 |
] |
| 444 |
|
| 445 |
for case in tests: |
| 446 |
do_test(*case) |