Passed
Push — master ( 05ccdf...015759 )
by Fabio
01:12
created

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

Complexity

Conditions 4

Size

Total Lines 10
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 10
rs 9.95
c 0
b 0
f 0
cc 4
nop 1
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 fsutil
7
8
9
def autodetect_format(s):
10
    if is_url(s) or is_filepath(s):
11
        return get_format_by_path(s)
12
    return None
13
14
15
def decode(s, format, **kwargs):
16
    serializer = get_serializer_by_format(format)
17
    if not serializer:
18
        raise ValueError('Invalid format: {}.'.format(format))
19
    decode_opts = kwargs.copy()
20
    data = serializer.decode(s.strip(), **decode_opts)
21
    return data
22
23
24
def encode(d, format, **kwargs):
25
    serializer = get_serializer_by_format(format)
26
    if not serializer:
27
        raise ValueError('Invalid format: {}.'.format(format))
28
    s = serializer.encode(d, **kwargs)
29
    return s
30
31
32
def is_data(s):
33
    return (len(s.splitlines()) > 1)
34
35
36
def is_filepath(s):
37
    if any([s.endswith(ext) for ext in get_serializers_extensions()]):
38
        return True
39
    return fsutil.is_file(s)
40
41
42
def is_url(s):
43
    return any([s.startswith(protocol)
44
                for protocol in ['http://', 'https://']])
45
46
47
def read_content(s):
48
    # s -> filepath or url or data
49
    if is_data(s):
50
        # data
51
        return s
52
    elif is_url(s):
53
        # url
54
        return read_url(s)
55
    elif is_filepath(s):
56
        # filepath
57
        return read_file(s)
58
    # one-line data?!
59
    return s
60
61
62
def read_file(filepath, **options):
63
    if fsutil.is_file(filepath):
64
        return fsutil.read_file(filepath, **options)
65
    return None
66
67
68
def read_url(url, **options):
69
    return fsutil.read_file_from_url(url, **options)
70
71
72
def write_file(filepath, content, **options):
73
    fsutil.write_file(filepath, content, **options)
74