Completed
Push — master ( 8473d5...821f0f )
by Felipe A.
01:23
created

by_python()   A

Complexity

Conditions 3

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
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, which
9
10
generic_mimetypes = {'application/octet-stream', None}
11
re_mime_validate = re.compile('\w+/\w+(; \w+=[^;]+)*')
12
13
def by_python(path):
14
    mime, encoding = mimetypes.guess_type(path)
15
    if mime in generic_mimetypes:
16
        return None
17
    return "%s%s%s" % (mime or "application/octet-stream", "; " if encoding else "", encoding or "")
18
19
if which('file'):
20
    def by_file(path):
21
        try:
22
            output = subprocess.check_output(("file", "-ib", path), universal_newlines=True).strip()
23
            if re_mime_validate.match(output) and not output in generic_mimetypes:
24
                # 'file' command can return status zero with invalid output
25
                return output
26
        except (subprocess.CalledProcessError, FileNotFoundError):
27
            pass
28
        return None
29
else:
30
    def by_file(path):
31
        return None
32
33
def by_default(path):
34
    return "application/octet-stream"
35