1"""
2Functions for dealing with mixed-case files from case-preserving file
3systems.
4
5Todo:
6
7  - handle patterns that already have brackets
8"""
9
10from __future__ import print_function
11import os
12import glob
13import fnmatch
14
15
16def ipat(pat):
17    """Convert glob pattern to case insensitive form."""
18
19    (dirname, pat) = os.path.split(pat)
20
21    # Convert '/path/to/test.fpt' => '/path/to/[Tt][Ee][Ss][Tt].[]'
22    newpat = ''
23    for c in pat:
24        if c.isalpha:
25            u = c.upper()
26            l = c.lower()
27            if u != l:
28                newpat = newpat + '[' + u + l + ']'
29            else:
30                newpat += c
31        else:
32            newpat += c
33
34    newpat = os.path.join(dirname, newpat)
35
36    return newpat
37
38def ifnmatch(name, pat):
39    """Case insensitive version of fnmatch.fnmatch()"""
40    return fnmatch.fnmatch(name, ipat(pat))
41
42def iglob(pat):
43    """Case insensitive version of glob.glob()"""
44    return glob.glob(ipat(pat))
45
46def ifind(pat, ext=None):
47    """Look for a file in a case insensitive way.
48
49    Returns filename it a matching file was found, or None if it was not.
50    """
51
52    if ext:
53        pat = os.path.splitext(pat)[0] + ext
54
55    files = iglob(pat)
56    if files:
57        return files[0]  # Return an arbitrary file
58    else:
59        return None
60
61__all__ = ['ipat', 'ifnmatch', 'iglob', 'ifind']
62