File size: 1,355 Bytes
19c6a63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
.. codeauthor:: Tsuyoshi Hombashi <[email protected]>
"""

import os
import stat
from errno import EBADF, ENOENT, ENOTDIR
from typing import Optional, Union

from ._binary_ext_checker import is_binary_ext_path


def is_fifo(file_path: Union[int, bytes, str]) -> bool:
    try:
        return stat.S_ISFIFO(os.stat(file_path).st_mode)
    except OSError as e:
        if e.errno not in (ENOENT, ENOTDIR, EBADF):
            raise

        return False
    except ValueError:
        return False


def to_codec_name(name: Optional[str]) -> Optional[str]:
    if not name:
        return None

    return name.lower().replace("-", "_")


def detect_file_encoding(file_path) -> Optional[str]:
    from chardet.universaldetector import UniversalDetector

    if not os.path.isfile(file_path) or is_binary_ext_path(file_path) or is_fifo(file_path):
        return None

    detector = UniversalDetector()
    READ_SIZE = 4 * 1024

    try:
        with open(file_path, mode="rb") as f:
            while True:
                binary = f.read(READ_SIZE)
                if not binary:
                    break

                detector.feed(binary)
                if detector.done:
                    break
    except OSError:
        return None
    finally:
        detector.close()

    return to_codec_name(detector.result.get("encoding"))