Completed
Push — master ( c18a49...b09083 )
by Felipe A.
53s
created

browsepy.file.unix_file()   A

Complexity

Conditions 4

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 4
dl 0
loc 10
rs 9.2
1
#!/usr/bin/env python
2
# -*- coding: UTF-8 -*-
3
4
import re
5
import subprocess
6
import mimetypes
7
8
from ..compat import FileNotFoundError, filter
9
10
generic_mimetypes = {'application/octet-stream', None}
11
re_mime_validate = re.compile('\w+/\w+(; \w+=[^;]+)*')
12
mimetype_methods = []
13
14
@mimetype_methods.append
15
def mimetypes_library(path):
16
    mime, encoding = mimetypes.guess_type(path)
17
    if mime in generic_mimetypes:
18
        return None
19
    return "%s%s%s" % (mime or "application/octet-stream", "; " if encoding else "", encoding or "")
20
21
@mimetype_methods.append
22
def unix_file(path):
23
    try:
24
        output = subprocess.check_output(("file", "-ib", path)).decode('utf8').strip()
25
        if re_mime_validate.match(output) and not output in generic_mimetypes:
26
            # 'file' command can return status zero with invalid output
27
            return output
28
    except (subprocess.CalledProcessError, FileNotFoundError):
29
        pass
30
    return None
31
32
def detect_mimetype(path):
33
    try:
34
        return next(filter(None, (method(path) for method in mimetype_methods)))
35
    except StopIteration:
36
        return "application/octet-stream"
37