Completed
Push — master ( a514df...9d2593 )
by Charles
9s
created

FileDumper.dump()   C

Complexity

Conditions 7

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
dl 0
loc 25
ccs 13
cts 13
cp 1
crap 7
rs 5.5
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
0 ignored issues
show
Coding Style introduced by
This module should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2
3 1
import csv
4 1
import json
5 1
import os
6
7 1
import xmltodict
0 ignored issues
show
Configuration introduced by
The import xmltodict could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
8 1
import yaml
0 ignored issues
show
Configuration introduced by
The import yaml could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
9
10 1
from git_app_version.helper.pyversion import PY3
11
12 1
try:
13 1
    import ConfigParser as configparser
14 1
except ImportError:
15 1
    import configparser
16
17
18 1
class FileDumper(object):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
19
20 1
    def dump(
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
best-practice introduced by
Too many arguments (9/5)
Loading history...
21
        self,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block.
self,
^ |
Loading history...
22
        data=None,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block.
data=None,
^ |
Loading history...
23
        fileformat='json',
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block.
fileformat='json',
^ |
Loading history...
24
        target=None,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block.
target=None,
^ |
Loading history...
25
        cwd=None,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block.
cwd=None,
^ |
Loading history...
26
        namespace='',
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block.
namespace='',
^ |
Loading history...
27
        csv_delimiter=',',
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block.
csv_delimiter=',',
^ |
Loading history...
28
        csv_quote='"',
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block.
csv_quote='"',
^ |
Loading history...
29
        csv_eol='lf'
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block.
csv_eol='lf'
^ |
Loading history...
30
    ):
31 1
        target = self.__check_target(target, cwd)
32 1
        if fileformat == 'yaml' or fileformat == 'yml':
33 1
            return self.dump_yaml(data, target, namespace)
34 1
        elif fileformat == 'xml':
35 1
            return self.dump_xml(data, target, namespace)
36 1
        elif fileformat == 'ini':
37 1
            return self.dump_ini(data, target, namespace)
38 1
        elif fileformat == 'sh':
39 1
            return self.dump_sh(data, target)
40 1
        elif fileformat == 'csv':
41 1
            return self.dump_csv(data, target, delimiter=csv_delimiter,
42
                                 quotechar=csv_quote, eol=csv_eol)
43
        else:
44 1
            return self.dump_json(data, target, namespace)
45
46 1
    def __check_target(self, target, cwd=None):
47 1
        if not os.path.isabs(target):
48 1
            cwd = cwd if cwd else os.getcwd()
49 1
            target = cwd + '/' + target
50
51 1
        self.__make_parent_dir(target)
52
53 1
        return target
54
55 1
    def __make_parent_dir(self, target):
0 ignored issues
show
Coding Style introduced by
This method could be written as a function/class method.

If a method does not access any attributes of the class, it could also be implemented as a function or static method. This can help improve readability. For example

class Foo:
    def some_method(self, x, y):
        return x + y;

could be written as

class Foo:
    @classmethod
    def some_method(cls, x, y):
        return x + y;
Loading history...
56 1
        parent_dir = os.path.dirname(target)
57 1
        if not os.path.exists(parent_dir):
58 1
            os.makedirs(parent_dir, 493)  # 493 in decimal as 755 in octal
59
60 1
    def __create_infos_to_dump(self, infos, namespace=None):
0 ignored issues
show
Coding Style introduced by
This method could be written as a function/class method.

If a method does not access any attributes of the class, it could also be implemented as a function or static method. This can help improve readability. For example

class Foo:
    def some_method(self, x, y):
        return x + y;

could be written as

class Foo:
    @classmethod
    def some_method(cls, x, y):
        return x + y;
Loading history...
61 1
        to_dump = infos
62 1
        if namespace is not None and namespace != '':
63 1
            namespaces = namespace.split('.')
64 1
            namespaces.reverse()
65 1
            for name in namespaces:
66 1
                to_dump = {name: to_dump}
67
68 1
        return to_dump
69
70 1
    def __encode(self, item, encoding='utf-8'):
0 ignored issues
show
Coding Style introduced by
This method could be written as a function/class method.

If a method does not access any attributes of the class, it could also be implemented as a function or static method. This can help improve readability. For example

class Foo:
    def some_method(self, x, y):
        return x + y;

could be written as

class Foo:
    @classmethod
    def some_method(cls, x, y):
        return x + y;
Loading history...
71
        if isinstance(item, unicode):
72
            return item.encode(encoding)
73
        else:
74
            return item
75
76 1
    def __flatten(self, item):
0 ignored issues
show
Coding Style introduced by
This method could be written as a function/class method.

If a method does not access any attributes of the class, it could also be implemented as a function or static method. This can help improve readability. For example

class Foo:
    def some_method(self, x, y):
        return x + y;

could be written as

class Foo:
    @classmethod
    def some_method(cls, x, y):
        return x + y;
Loading history...
77
        if isinstance(item, list):
78
            flattened_list = ''
79
            if len(item):
80
                flattened_list = "'{}'".format("', '".join(item))
81
            return "[{}]".format(flattened_list)
82
        else:
83
            return item
84
85 1
    def dump_sh(self, data, target):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
86 1
        target = target + '.sh'
87
88 1
        with open(target, 'w') as fpt:
89 1
            for key, val in data.items():
90 1
                if not PY3:
91
                    val = self.__encode(self.__flatten(val))
92 1
                fpt.write("{}=\"{}\"\n".format(key, val))
93
94 1
        return target
95
96 1
    def dump_csv(self, data, target, delimiter=',', quotechar='"', eol='lf'):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
best-practice introduced by
Too many arguments (6/5)
Loading history...
97 1
        target = target + '.csv'
98
99 1
        eol = "\r\n" if eol == 'crlf' or eol == "\r\n" else "\n"
100
101 1
        csv.register_dialect('custom', delimiter=str(delimiter),
102
                             lineterminator=str(eol), quotechar=str(quotechar),
103
                             quoting=csv.QUOTE_MINIMAL)
104
105 1
        if PY3:
106 1
            with open(target, 'w', encoding='utf-8') as fpt:
107 1
                writer = csv.writer(fpt, dialect='custom')
108 1
                for key, val in data.items():
109 1
                    writer.writerow((key, val))
110
        else:
111
            with open(target, 'wb') as fpt:
112
                writer = csv.writer(fpt, dialect='custom')
113
                for key, val in data.items():
114
                    val = self.__encode(self.__flatten(val))
115
                    writer.writerow((key, val))
116
117 1
        return target
118
119 1
    def dump_ini(self, data, target, namespace=None):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
120 1
        target = target + '.ini'
121
122 1
        if namespace is None or namespace == '':
123 1
            namespace = 'app_version'
124
125 1
        ini = configparser.RawConfigParser()
126 1
        ini.add_section(namespace)
127
128 1
        for key, val in data.items():
129 1
            if not PY3:
130
                val = self.__encode(self.__flatten(val))
131
132 1
            ini.set(namespace, key, val)
133
134 1
        with open(target, 'w') as fpt:
135 1
            ini.write(fpt)
136
137 1
        return target
138
139 1
    def dump_xml(self, data, target, namespace=None):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
140 1
        target = target + '.xml'
141 1
        if namespace is None or namespace == '':
142 1
            namespace = 'app_version'
143
144 1
        with open(target, 'w') as fpt:
145 1
            xml = xmltodict.unparse(
146
                self.__create_infos_to_dump(
147
                    data,
148
                    namespace),
149
                encoding='utf-8',
150
                pretty=True,
151
                indent='  ')
152 1
            if not PY3:
153
                xml = xml.encode('utf-8')
154
155 1
            fpt.write(xml)
156
157 1
            return target
158
159 1
    def dump_json(self, data, target, namespace=None):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
160 1
        target = target + '.json'
161
162 1
        data1 = self.__create_infos_to_dump(data, namespace)
163
164 1
        with open(target, 'w') as fpt:
165 1
            json.dump(data1, fpt, indent=2)
166
167 1
        return target
168
169 1
    def dump_yaml(self, data, target, namespace=None):
0 ignored issues
show
Coding Style introduced by
This method should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
170 1
        target = target + '.yml'
171
172 1
        with open(target, 'w') as fpt:
173 1
            if not data:
174 1
                fpt.write("---\n")
175
            else:
176 1
                yaml.safe_dump(
177
                    self.__create_infos_to_dump(data, namespace),
178
                    fpt,
179
                    default_flow_style=False,
180
                    explicit_start=True,
181
                    allow_unicode=True,
182
                    # force quoting
183
                    # to prevent abbrev_commit to be read as a float
184
                    default_style='\''
185
                )
186
187
        return target
188