Completed
Push — master ( 7c0f11...307a39 )
by Fabio
03:52
created

benedict.dicts.io.io_util.autodetect_format()   A

Complexity

Conditions 4

Size

Total Lines 6
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 4
nop 2
1
# -*- coding: utf-8 -*-
2
3
from benedict.serializers import (
4
    get_format_by_path, get_serializer_by_format, get_serializers_extensions, )
5
6
import errno
7
import os
8
import requests
9
10
11
def autodetect_format(s, default=None):
12
    if is_data(s):
13
        return default
14
    elif is_url(s) or is_filepath(s):
15
        return get_format_by_path(s)
16
    return default
17
18
19
def decode(s, format, **kwargs):
20
    serializer = get_serializer_by_format(format)
21
    if not serializer:
22
        raise ValueError('Invalid format: {}.'.format(format))
23
    decode_opts = kwargs.copy()
24
    data = serializer.decode(s.strip(), **decode_opts)
25
    return data
26
27
28
def encode(d, format, **kwargs):
29
    serializer = get_serializer_by_format(format)
30
    if not serializer:
31
        raise ValueError('Invalid format: {}.'.format(format))
32
    s = serializer.encode(d, **kwargs)
33
    return s
34
35
36
def is_data(s):
37
    return (len(s.splitlines()) > 1)
38
39
40
def is_filepath(s):
41
    return any([s.endswith(extension)
42
                for extension in get_serializers_extensions()])
43
44
45
def is_url(s):
46
    return any([s.startswith(protocol)
47
                for protocol in ['http://', 'https://']])
48
49
50
def read_content(s):
51
    # s -> filepath or url or data
52
    if is_data(s):
53
        # data
54
        return s
55
    elif is_url(s):
56
        # url
57
        return read_url(s)
58
    elif is_filepath(s):
59
        # filepath
60
        return read_file(s)
61
    # one-line data?!
62
    return s
63
64
65
def read_file(filepath):
66
    if os.path.isfile(filepath):
67
        content = ''
68
        with open(filepath, 'r') as file:
69
            content = file.read()
70
        return content
71
    return None
72
73
74
def read_url(url, *args, **kwargs):
75
    response = requests.get(url, *args, **kwargs)
76
    if response.status_code == requests.codes.ok:
77
        content = response.text
78
        return content
79
    raise ValueError(
80
        'Invalid url response status code: {}.'.format(
81
            response.status_code))
82
83
84
def write_file_dir(filepath):
85
    filedir = os.path.dirname(filepath)
86
    if os.path.exists(filedir):
87
        return
88
    try:
89
        os.makedirs(filedir)
90
    except OSError as e:
91
        # Guard against race condition
92
        if e.errno != errno.EEXIST:
93
            raise e
94
95
96
def write_file(filepath, content):
97
    # https://stackoverflow.com/questions/12517451/automatically-creating-directories-with-file-output
98
    write_file_dir(filepath)
99
    with open(filepath, 'w+') as file:
100
        file.write(content)
101
    return True
102