summaryrefslogtreecommitdiffstats
path: root/Lib/zipfile/_path/glob.py
blob: 4a2e665e27078aad32e2be2a43f02532cb99725d (plain)
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
import re


def translate(pattern):
    r"""
    Given a glob pattern, produce a regex that matches it.

    >>> translate('*.txt')
    '[^/]*\\.txt'
    >>> translate('a?txt')
    'a.txt'
    >>> translate('**/*')
    '.*/[^/]*'
    """
    return ''.join(map(replace, separate(pattern)))


def separate(pattern):
    """
    Separate out character sets to avoid translating their contents.

    >>> [m.group(0) for m in separate('*.txt')]
    ['*.txt']
    >>> [m.group(0) for m in separate('a[?]txt')]
    ['a', '[?]', 'txt']
    """
    return re.finditer(r'([^\[]+)|(?P<set>[\[].*?[\]])|([\[][^\]]*$)', pattern)


def replace(match):
    """
    Perform the replacements for a match from :func:`separate`.
    """

    return match.group('set') or (
        re.escape(match.group(0))
        .replace('\\*\\*', r'.*')
        .replace('\\*', r'[^/]*')
        .replace('\\?', r'.')
    )