xref: /aosp_15_r20/external/fonttools/Lib/fontTools/misc/macCreatorType.py (revision e1fe3e4ad2793916b15cccdc4a7da52a7e1dd0e9)
1from fontTools.misc.textTools import Tag, bytesjoin, strjoin
2
3try:
4    import xattr
5except ImportError:
6    xattr = None
7
8
9def _reverseString(s):
10    s = list(s)
11    s.reverse()
12    return strjoin(s)
13
14
15def getMacCreatorAndType(path):
16    """Returns file creator and file type codes for a path.
17
18    Args:
19            path (str): A file path.
20
21    Returns:
22            A tuple of two :py:class:`fontTools.textTools.Tag` objects, the first
23            representing the file creator and the second representing the
24            file type.
25    """
26    if xattr is not None:
27        try:
28            finderInfo = xattr.getxattr(path, "com.apple.FinderInfo")
29        except (KeyError, IOError):
30            pass
31        else:
32            fileType = Tag(finderInfo[:4])
33            fileCreator = Tag(finderInfo[4:8])
34            return fileCreator, fileType
35    return None, None
36
37
38def setMacCreatorAndType(path, fileCreator, fileType):
39    """Set file creator and file type codes for a path.
40
41    Note that if the ``xattr`` module is not installed, no action is
42    taken but no error is raised.
43
44    Args:
45            path (str): A file path.
46            fileCreator: A four-character file creator tag.
47            fileType: A four-character file type tag.
48
49    """
50    if xattr is not None:
51        from fontTools.misc.textTools import pad
52
53        if not all(len(s) == 4 for s in (fileCreator, fileType)):
54            raise TypeError("arg must be string of 4 chars")
55        finderInfo = pad(bytesjoin([fileType, fileCreator]), 32)
56        xattr.setxattr(path, "com.apple.FinderInfo", finderInfo)
57