Skip to content

Commit cd96255

Browse files
Run openwisp-qa-format over files
1 parent cdaf8c5 commit cd96255

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

50 files changed

+1236
-1255
lines changed

docs/source/conf.py

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -33,35 +33,35 @@
3333
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
3434
# ones.
3535
extensions = [
36-
'sphinx.ext.autodoc',
37-
'sphinx.ext.viewcode',
36+
"sphinx.ext.autodoc",
37+
"sphinx.ext.viewcode",
3838
]
3939

4040
# Add any paths that contain templates here, relative to this directory.
41-
templates_path = ['_templates']
41+
templates_path = ["_templates"]
4242

4343
# The suffix(es) of source filenames.
4444
# You can specify multiple suffix as a list of string:
4545
# source_suffix = ['.rst', '.md']
46-
source_suffix = '.rst'
46+
source_suffix = ".rst"
4747

4848
# The encoding of source files.
4949
# source_encoding = 'utf-8-sig'
5050

5151
# The master toctree document.
52-
master_doc = 'index'
52+
master_doc = "index"
5353

5454
# General information about the project.
55-
project = u'netjsonconfig'
56-
copyright = u'{0}, OpenWISP.org'.format(datetime.date.today().year)
57-
author = u'Federico Capoano'
55+
project = u"netjsonconfig"
56+
copyright = u"{0}, OpenWISP.org".format(datetime.date.today().year)
57+
author = u"Federico Capoano"
5858

5959
# The version info for the project you're documenting, acts as replacement for
6060
# |version| and |release|, also used in various other places throughout the
6161
# built documents.
6262
#
6363
# The short X.Y version.
64-
version = '{0}.{1}'.format(VERSION[0], VERSION[1])
64+
version = "{0}.{1}".format(VERSION[0], VERSION[1])
6565
# The full version, including alpha/beta/rc tags.
6666
release = get_version()
6767

@@ -98,7 +98,7 @@
9898
# show_authors = False
9999

100100
# The name of the Pygments (syntax highlighting) style to use.
101-
pygments_style = 'sphinx'
101+
pygments_style = "sphinx"
102102

103103
# A list of ignored prefixes for module index sorting.
104104
# modindex_common_prefix = []
@@ -114,7 +114,7 @@
114114

115115
# The theme to use for HTML and HTML Help pages. See the documentation for
116116
# a list of builtin themes.
117-
html_theme = 'sphinx_rtd_theme'
117+
html_theme = "sphinx_rtd_theme"
118118

119119
# Theme options are theme-specific and customize the look and feel of a theme
120120
# further. For a list of options available for each theme, see the
@@ -206,7 +206,7 @@
206206
# html_search_scorer = 'scorer.js'
207207

208208
# Output file base name for HTML help builder.
209-
htmlhelp_basename = 'netjsonconfigdoc'
209+
htmlhelp_basename = "netjsonconfigdoc"
210210

211211
# -- Options for LaTeX output ---------------------------------------------
212212

@@ -227,10 +227,10 @@
227227
latex_documents = [
228228
(
229229
master_doc,
230-
'netjsonconfig.tex',
231-
u'netjsonconfig documentation',
232-
u'Federico Capoano',
233-
'manual',
230+
"netjsonconfig.tex",
231+
u"netjsonconfig documentation",
232+
u"Federico Capoano",
233+
"manual",
234234
),
235235
]
236236

@@ -259,7 +259,7 @@
259259

260260
# One entry per manual page. List of tuples
261261
# (source start file, name, description, authors, manual section).
262-
man_pages = [(master_doc, 'netjsonconfig', u'netjsonconfig Documentation', [author], 1)]
262+
man_pages = [(master_doc, "netjsonconfig", u"netjsonconfig Documentation", [author], 1)]
263263

264264
# If true, show URL addresses after external links.
265265
# man_show_urls = False
@@ -273,12 +273,12 @@
273273
texinfo_documents = [
274274
(
275275
master_doc,
276-
'netjsonconfig',
277-
u'netjsonconfig documentation',
276+
"netjsonconfig",
277+
u"netjsonconfig documentation",
278278
author,
279-
'netjsonconfig',
280-
'Python library that converts NetJSON DeviceConfiguration objects to real router configurations.',
281-
'Miscellaneous',
279+
"netjsonconfig",
280+
"Python library that converts NetJSON DeviceConfiguration objects to real router configurations.",
281+
"Miscellaneous",
282282
),
283283
]
284284

@@ -341,7 +341,7 @@
341341
# epub_post_files = []
342342

343343
# A list of files that should not be packed into the epub file.
344-
epub_exclude_files = ['search.html']
344+
epub_exclude_files = ["search.html"]
345345

346346
# The depth of the table of contents in toc.ncx.
347347
# epub_tocdepth = 3

netjsonconfig/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,13 @@
1010

1111
def get_backends():
1212
default = {
13-
'openwrt': OpenWrt,
14-
'openwisp': OpenWisp,
15-
'openvpn': OpenVpn,
13+
"openwrt": OpenWrt,
14+
"openwisp": OpenWisp,
15+
"openvpn": OpenVpn,
1616
}
1717
logger = logging.getLogger(__name__)
1818

19-
for entry_point in iter_entry_points('netjsonconfig.backends'):
19+
for entry_point in iter_entry_points("netjsonconfig.backends"):
2020
try:
2121
default.update({entry_point.name.lower(): entry_point.load()})
2222
except ImportError as e: # noqa

netjsonconfig/backends/base/backend.py

Lines changed: 36 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ class BaseBackend(object):
2020
"""
2121

2222
schema = None
23-
FILE_SECTION_DELIMITER = '# ---------- files ---------- #'
23+
FILE_SECTION_DELIMITER = "# ---------- files ---------- #"
2424
list_identifiers = []
2525

2626
def __init__(self, config=None, native=None, templates=None, context=None):
@@ -48,8 +48,8 @@ def __init__(self, config=None, native=None, templates=None, context=None):
4848
self.parse(native)
4949
else:
5050
raise ValueError(
51-
'Expecting either config or native argument to be '
52-
'passed during the initialization of the backend'
51+
"Expecting either config or native argument to be "
52+
"passed during the initialization of the backend"
5353
)
5454

5555
def _load(self, config):
@@ -63,7 +63,7 @@ def _load(self, config):
6363
pass
6464
if not isinstance(config, dict):
6565
raise TypeError(
66-
'config block must be an instance of dict or a valid NetJSON string'
66+
"config block must be an instance of dict or a valid NetJSON string"
6767
)
6868
return config
6969

@@ -75,7 +75,7 @@ def _merge_config(self, config, templates):
7575
return config
7676
# type check
7777
if not isinstance(templates, list):
78-
raise TypeError('templates argument must be an instance of list')
78+
raise TypeError("templates argument must be an instance of list")
7979
# merge templates with main configuration
8080
result = {}
8181
config_list = templates + [config]
@@ -97,33 +97,33 @@ def _render_files(self):
9797
"""
9898
Renders additional files specified in ``self.config['files']``
9999
"""
100-
output = ''
100+
output = ""
101101
# render files
102-
files = self.config.get('files', [])
102+
files = self.config.get("files", [])
103103
# add delimiter
104104
if files:
105-
output += '\n{0}\n\n'.format(self.FILE_SECTION_DELIMITER)
105+
output += "\n{0}\n\n".format(self.FILE_SECTION_DELIMITER)
106106
for f in files:
107-
mode = f.get('mode', DEFAULT_FILE_MODE)
107+
mode = f.get("mode", DEFAULT_FILE_MODE)
108108
# add file to output
109109
file_output = (
110-
'# path: {0}\n'
111-
'# mode: {1}\n\n'
112-
'{2}\n\n'.format(f['path'], mode, f['contents'])
110+
"# path: {0}\n"
111+
"# mode: {1}\n\n"
112+
"{2}\n\n".format(f["path"], mode, f["contents"])
113113
)
114114
output += file_output
115115
return output
116116

117117
def _deduplicate_files(self):
118-
files = self.config.get('files', [])
118+
files = self.config.get("files", [])
119119
if not files:
120120
return
121121
files_dict = OrderedDict()
122122
for file in files:
123-
files_dict[file['path']] = file
124-
self.config['files'] = list(files_dict.values())
123+
files_dict[file["path"]] = file
124+
self.config["files"] = list(files_dict.values())
125125

126-
@draft4_format_checker.checks('cidr', AssertionError)
126+
@draft4_format_checker.checks("cidr", AssertionError)
127127
def _cidr_notation(value):
128128
try:
129129
ipaddress.ip_network(value)
@@ -153,9 +153,9 @@ def render(self, files=True):
153153
self.to_intermediate()
154154
self._deduplicate_files()
155155
# support multiple renderers
156-
renderers = getattr(self, 'renderers', None) or [self.renderer]
156+
renderers = getattr(self, "renderers", None) or [self.renderer]
157157
# convert intermediate data structure to native configuration
158-
output = ''
158+
output = ""
159159
for renderer_class in renderers:
160160
renderer = renderer_class(self)
161161
output += renderer.render()
@@ -168,7 +168,7 @@ def render(self, files=True):
168168
files_output = self._render_files()
169169
if files_output:
170170
# max 2 new lines
171-
output += files_output.replace('\n\n\n', '\n\n')
171+
output += files_output.replace("\n\n\n", "\n\n")
172172
# return the configuration
173173
return output
174174

@@ -185,7 +185,7 @@ def json(self, validate=True, *args, **kwargs):
185185
self.validate()
186186
# automatically adds NetJSON type
187187
config = deepcopy(self.config)
188-
config.update({'type': 'DeviceConfiguration'})
188+
config.update({"type": "DeviceConfiguration"})
189189
return json.dumps(config, *args, **kwargs)
190190

191191
def generate(self):
@@ -196,7 +196,7 @@ def generate(self):
196196
:returns: in-memory tar.gz archive, instance of ``BytesIO``
197197
"""
198198
tar_bytes = BytesIO()
199-
tar = tarfile.open(fileobj=tar_bytes, mode='w')
199+
tar = tarfile.open(fileobj=tar_bytes, mode="w")
200200
self._generate_contents(tar)
201201
self._process_files(tar)
202202
tar.close()
@@ -206,7 +206,7 @@ def generate(self):
206206
# to achieve this we must use the python `gzip` library because the `tarfile`
207207
# library does not seem to offer the possibility to modify the gzip `mtime`.
208208
gzip_bytes = BytesIO()
209-
gz = gzip.GzipFile(fileobj=gzip_bytes, mode='wb', mtime=0)
209+
gz = gzip.GzipFile(fileobj=gzip_bytes, mode="wb", mtime=0)
210210
gz.write(tar_bytes.getvalue())
211211
gz.close()
212212
gzip_bytes.seek(0) # set pointer to beginning of stream
@@ -215,7 +215,7 @@ def generate(self):
215215
def _generate_contents(self, tar):
216216
raise NotImplementedError()
217217

218-
def write(self, name, path='./'):
218+
def write(self, name, path="./"):
219219
"""
220220
Like ``generate`` but writes to disk.
221221
@@ -224,10 +224,10 @@ def write(self, name, path='./'):
224224
:returns: None
225225
"""
226226
byte_object = self.generate()
227-
file_name = '{0}.tar.gz'.format(name)
228-
if not path.endswith('/'):
229-
path += '/'
230-
f = open('{0}{1}'.format(path, file_name), 'wb')
227+
file_name = "{0}.tar.gz".format(name)
228+
if not path.endswith("/"):
229+
path += "/"
230+
f = open("{0}{1}".format(path, file_name), "wb")
231231
f.write(byte_object.getvalue())
232232
f.close()
233233

@@ -239,16 +239,16 @@ def _process_files(self, tar):
239239
:returns: None
240240
"""
241241
# insert additional files
242-
for file_item in self.config.get('files', []):
243-
path = file_item['path']
242+
for file_item in self.config.get("files", []):
243+
path = file_item["path"]
244244
# remove leading slashes from path
245-
if path.startswith('/'):
245+
if path.startswith("/"):
246246
path = path[1:]
247247
self._add_file(
248248
tar=tar,
249249
name=path,
250-
contents=file_item['contents'],
251-
mode=file_item.get('mode', DEFAULT_FILE_MODE),
250+
contents=file_item["contents"],
251+
mode=file_item.get("mode", DEFAULT_FILE_MODE),
252252
)
253253

254254
def _add_file(self, tar, name, contents, mode=DEFAULT_FILE_MODE):
@@ -261,7 +261,7 @@ def _add_file(self, tar, name, contents, mode=DEFAULT_FILE_MODE):
261261
:param mode: string representing file mode, defaults to 644
262262
:returns: None
263263
"""
264-
byte_contents = BytesIO(contents.encode('utf8'))
264+
byte_contents = BytesIO(contents.encode("utf8"))
265265
info = tarfile.TarInfo(name=name)
266266
info.size = len(contents)
267267
# mtime must be 0 or any checksum operation
@@ -292,16 +292,16 @@ def to_intermediate(self):
292292
value = OrderedDict(value)
293293
if value:
294294
self.intermediate_data = merge_config(
295-
self.intermediate_data, value, list_identifiers=['.name']
295+
self.intermediate_data, value, list_identifiers=[".name"]
296296
)
297297

298298
def parse(self, native):
299299
"""
300300
Parses a native configuration and converts
301301
it to a NetJSON configuration dictionary
302302
"""
303-
if not hasattr(self, 'parser') or not self.parser:
304-
raise NotImplementedError('Parser class not specified')
303+
if not hasattr(self, "parser") or not self.parser:
304+
raise NotImplementedError("Parser class not specified")
305305
parser = self.parser(native)
306306
self.intermediate_data = parser.intermediate_data
307307
del parser

netjsonconfig/backends/base/converter.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,18 +43,18 @@ def type_cast(self, item, schema=None):
4343
"""
4444
if schema is None:
4545
schema = self._schema
46-
properties = schema['properties']
46+
properties = schema["properties"]
4747
for key, value in item.items():
4848
if key not in properties:
4949
continue
5050
try:
51-
json_type = properties[key]['type']
51+
json_type = properties[key]["type"]
5252
except KeyError:
5353
json_type = None
54-
if json_type == 'integer' and not isinstance(value, int):
54+
if json_type == "integer" and not isinstance(value, int):
5555
value = int(value)
56-
elif json_type == 'boolean' and not isinstance(value, bool):
57-
value = value == '1'
56+
elif json_type == "boolean" and not isinstance(value, bool):
57+
value = value == "1"
5858
item[key] = value
5959
return item
6060

netjsonconfig/backends/base/parser.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,10 @@ def __init__(self, config):
1313
data = self.parse_text(config)
1414
# presence of read() method
1515
# indicates a file-like object
16-
elif hasattr(config, 'read'):
16+
elif hasattr(config, "read"):
1717
data = self.parse_tar(config)
1818
else:
19-
raise ParseError('Unrecognized format')
19+
raise ParseError("Unrecognized format")
2020
self.intermediate_data = data
2121

2222
def parse_text(self, config):

0 commit comments

Comments
 (0)