File: pattern.py

package info (click to toggle)
crazy-complete 0.3.7-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,528 kB
  • sloc: python: 13,342; sh: 995; makefile: 68
file content (446 lines) | stat: -rw-r--r-- 12,768 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2025-2026 Benjamin Abendroth <braph93@gmx.de>

'''This module contains functions for transforming bash glob patterns.'''


from .string_stream import StringStream


class PatternBase:
    '''Base class for glob patterns.'''

    def to_regex(self):
        '''Make a regular expression.'''
        raise NotImplementedError

    def to_zsh_glob(self):
        '''Make a Zsh glob.'''
        raise NotImplementedError


class Literal(PatternBase):
    '''Holds a literal string.'''

    REGEX_ESCAPE_CHARS = '.?*+|{}[]()'

    def __init__(self, string):
        self.string = string

    def __str__(self):
        return self.string

    def __repr__(self):
        return self.string

    def to_regex(self):
        string = self.string

        for c in Literal.REGEX_ESCAPE_CHARS:
            string = string.replace(c, f'\\{c}')

        return string

    def to_zsh_glob(self):
        string = ''

        for c in self.string:
            if c in ('[', ']', '?', '*', '"', ' ', '\\'):
                string += f"'{c}'"
            elif c == "'":
                string += f'"{c}"'
            else:
                string += c

        return string


class Star(PatternBase):
    '''Represents a star glob (*).'''

    def to_regex(self):
        return '.*'

    def to_zsh_glob(self):
        return '*'


class Question(PatternBase):
    '''Represents a question glob (?).'''

    def to_regex(self):
        return '.'

    def to_zsh_glob(self):
        return '?'


class CharClass(PatternBase):
    '''Represents a character class.'''

    REGEX_ESCAPE_CHARS = r'^\.[]'

    def __init__(self, chars, negated):
        self.chars = chars
        self.negated = negated

    def to_regex(self):
        chars = self.chars

        for c in CharClass.REGEX_ESCAPE_CHARS:
            chars = chars.replace(c, f'\\{c}')

        if self.negated:
            return f'[^{chars}]'

        return f'[{chars}]'

    def to_zsh_glob(self):
        chars = ''

        for c in self.chars:
            if c in ('[', ']', '!'):
                chars += f"'{c}'"
            else:
                chars += c

        if self.negated:
            return f'[!{chars}]'

        return f'[{chars}]'


class ExtGlob(PatternBase):
    '''Holds an extglob: @(), *(), ?(), +(), !().'''

    def __init__(self, type_, alternatives):
        self.type = type_
        self.alternatives = alternatives

    def to_regex(self):
        r = []

        for alternative in self.alternatives:
            r.append(alternative.to_regex())

        p = '(%s)' % '|'.join(r)

        if self.type == '@':
            return p

        if self.type == '*':
            return p + '*'

        if self.type == '+':
            return p + '+'

        if self.type == '?':
            return p + '?'

        if self.type == '!':
            raise ValueError('Negated glob !(...) not supported in regex')

        raise AssertionError("Not reached")

    def to_zsh_glob(self):
        r = []

        for alternative in self.alternatives:
            r.append(alternative.to_zsh_glob())

        p = '(%s)' % '|'.join(r)

        if self.type == '@':
            return p

        if self.type in ('*', '+', '?', '!'):
            raise ValueError(f'Extended glob of form {self.type}(...) not supported in zsh glob')

        raise AssertionError("Not reached")


class PatternList(PatternBase):
    '''Holds a list of patterns.'''

    def __init__(self):
        self.tokens = []

    def to_regex(self):
        return ''.join(t.to_regex() for t in self.tokens)

    def to_zsh_glob(self):
        return ''.join(t.to_zsh_glob() for t in self.tokens)

    def append(self, token):
        '''Add a token.'''
        self.tokens.append(token)


EXTGLOB_TOKENS = ('@(', '*(', '+(', '?(', '!(', '+(')
EXTGLOB_TOKENS_PRE = ('@', '*', '+', '?', '!', '+')


class GlobLexer(StringStream):
    '''Class for splitting a pattern into tokens.'''

    def __init__(self, pattern):
        super().__init__(pattern)
        self.tokens = []

    def parse(self):
        '''Split string into tokens.'''
        tokens = []

        while True:
            try:
                tokens.append(self._parse_token())
            except IndexError:
                return tokens

    def _parse_token(self):
        c = self.get()

        if c in EXTGLOB_TOKENS_PRE and self.peek() == '(':
            return f'{c}{self.get()}'

        if c in ('[', ']', ')', '?', '!', '*', '|'):
            return c

        if c == '"':
            return Literal(self.parse_shell_double_quote(in_quotes=True))

        if c == "'":
            return Literal(self.parse_shell_single_quote(in_quotes=True))

        literal = c
        while True:
            c = self.peek()
            if c is None:
                break
            if c in EXTGLOB_TOKENS_PRE and self.peek(1) == '(':
                break
            if c in ('*', '?', '[', ']', ')', '|', '"', "'"):
                break
            literal += c
            self.get()

        return Literal(literal)


class GlobParser:
    '''Parses tokens from GlobLexer.'''

    def __init__(self, tokens):
        self.tokens = tokens
        self.i = 0

    def get(self):
        '''Return a token and advance position.'''
        token = self.tokens[self.i]
        self.i += 1
        return token

    def peek(self):
        '''Return current token without advancing the position.'''
        try:
            return self.tokens[self.i]
        except IndexError:
            return None

    def have(self):
        '''Return True if there are any tokens left.'''
        return self.i < len(self.tokens)

    def parse(self):
        '''Parse tokens and return a PatternList object.'''
        root = PatternList()
        while self.have():
            root.append(self._parse_token())
        return root

    def _parse_char_class(self):
        chars = ''
        negated = False

        try:
            token = self.get()
        except IndexError as e:
            raise ValueError('Unclosed character class') from e

        if token == '!':
            negated = True
        elif token == ']':
            raise ValueError('Empty character class')
        else:
            chars += str(token)

        while True:
            try:
                token = self.get()
            except IndexError as e:
                raise ValueError('Unclosed character class') from e

            if token == ']':
                return CharClass(chars, negated)

            chars += str(token)

    def _parse_ext_glob(self, token):
        type_ = token[0]
        alternatives = [PatternList()]

        while True:
            token = self.peek()

            if token == ')':
                self.get()
                return ExtGlob(type_, alternatives)

            if token == '|':
                self.get()
                alternatives.append(PatternList())
            elif token is None:
                raise ValueError('Unclosed extglob')
            else:
                alternatives[-1].append(self._parse_token())

    def _parse_token(self):
        token = self.get()

        if token == '[':
            return self._parse_char_class()

        if token == '*':
            return Star()

        if token == '?':
            return Question()

        if token in EXTGLOB_TOKENS:
            return self._parse_ext_glob(token)

        return token


def bash_glob_to_regex(pattern):
    '''Transform a bash glob to regex.'''

    tokens = GlobLexer(pattern).parse()
    tokens = GlobParser(tokens).parse()
    return tokens.to_regex()


def bash_glob_to_zsh_glob(pattern):
    '''Transform a bash glob to zsh glob.'''

    tokens = GlobLexer(pattern).parse()
    tokens = GlobParser(tokens).parse()
    return tokens.to_zsh_glob()


def test():
    '''Tests.'''

    def do_test(num, bash_pattern, expected_regex, expected_zsh_glob):
        '''Do a test case.'''

        try:
            regex_result = bash_glob_to_regex(bash_pattern)
        except ValueError:
            regex_result = ValueError

        try:
            zsh_glob_result = bash_glob_to_zsh_glob(bash_pattern)
        except ValueError:
            zsh_glob_result = ValueError

        if regex_result != expected_regex:
            print('Test %d (regex):' % num)
            print('Having:   %s' % regex_result)
            print('Expected: %s' % expected_regex)
            raise AssertionError('Test failed')

        if zsh_glob_result != expected_zsh_glob:
            print('Test %d (zsh glob):' % num)
            print('Having:   %s' % zsh_glob_result)
            print('Expected: %s' % expected_zsh_glob)
            raise AssertionError('Test failed')

    tests = [
        # Literals
        (0,  r'a',                   r'a',                  r'a'),
        (1,  r'abc',                 r'abc',                r'abc'),
        (3,  r'"abc"',               r'abc',                r'abc'),
        (4,  r"'abc'",               r'abc',                r'abc'),
        (5,  r"'a'b'c'",             r'abc',                r'abc'),
        (6,  r'.',                   r'\.',                 r'.'),
        (7,  r'+',                   r'\+',                 r'+'),
        (8,  r'@',                   r'@',                  r'@'),
        (9,  r'"["',                 r'\[',                 r"'['"),
        (10, r"'['",                 r'\[',                 r"'['"),
        (11, r'"]"',                 r'\]',                 r"']'"),
        (12, r"']'",                 r'\]',                 r"']'"),
        (13, r"'*'",                 r'\*',                 r"'*'"),
        (14, r"'?'",                 r'\?',                 r"'?'"),

        # Simple globbing
        (15, r'*',                   r'.*',                 r'*'),
        (16, r'?',                   r'.',                  r'?'),
        (17, r'???',                 r'...',                r'???'),

        # Literals + simple globbing
        (18, r'*abc*',               r'.*abc.*',            r'*abc*'),
        (19, r'*.*',                 r'.*\..*',             r'*.*'),
        (20, r'*+*',                 r'.*\+.*',             r'*+*'),

        # Character classes
        (21, r'[abc]',               r'[abc]',              r'[abc]'),
        (22, r'[.]',                 r'[\.]',               r'[.]'),
        (23, r'[+]',                 r'[+]',                r'[+]'),
        (24, r'[}]',                 r'[}]',                r'[}]'),
        (25, r'[{]',                 r'[{]',                r'[{]'),
        (26, r'[*]',                 r'[*]',                r'[*]'),
        (27, r'[(]',                 r'[(]',                r'[(]'),
        (28, r'[)]',                 r'[)]',                r'[)]'),
        (29, r'["["]',               r'[\[]',               r"['[']"),
        (30, r'["]"]',               r'[\]]',               r"[']']"),

        # Extglob @
        (31, r'@(foo)',              r'(foo)',              r'(foo)'),
        (32, r'@(foo|bar)',          r'(foo|bar)',          r'(foo|bar)'),
        (33, r'@(|foo)',             r'(|foo)',             r'(|foo)'),

        # Extglob *
        (34, r'*(foo|bar)',          r'(foo|bar)*',         ValueError),
        (35, r'*(foo)',              r'(foo)*',             ValueError),
        (36, r'*(|foo)',             r'(|foo)*',            ValueError),

        # Extglob +
        (37, r'+(foo|bar)',          r'(foo|bar)+',         ValueError),
        (38, r'+(foo)',              r'(foo)+',             ValueError),
        (39, r'+(|foo)',             r'(|foo)+',            ValueError),

        # Extglob ?
        (40, r'?(foo|bar)',          r'(foo|bar)?',         ValueError),
        (41, r'?(foo)',              r'(foo)?',             ValueError),
        (42, r'?(|foo)',             r'(|foo)?',            ValueError),

        # Extglob !
        (43, r'!(foo|bar)',          ValueError,            ValueError),

        # Nested
        (44, r'@([abc]|foo)',        r'([abc]|foo)',        r'([abc]|foo)'),
        (45, r'@(@(foo|bar))',       r'((foo|bar))',        r'((foo|bar))'),
        (46, r'@(@("foo"|bar))',     r'((foo|bar))',        r'((foo|bar))'),
        (47, r'@(?|bar)',            r'(.|bar)',            r'(?|bar)'),
        (48, r'@(*baz|bar)',         r'(.*baz|bar)',        r'(*baz|bar)'),

        # Syntax errors
        (70, r'@(foo',               ValueError,            ValueError),
        (71, r'[abc',                ValueError,            ValueError),
        (71, r'"abc',                ValueError,            ValueError),
        (71, r"'abc",                ValueError,            ValueError),
    ]

    for case in tests:
        do_test(*case)