Skip to content

Commit

Permalink
Blacken Python code
Browse files Browse the repository at this point in the history
Use black to format the Python code:

```
black -l 99 ionit ionit_plugin.py setup.py tests
```

Signed-off-by: Benjamin Drung <[email protected]>
  • Loading branch information
bdrung committed Sep 28, 2020
1 parent a1de5f6 commit 6ece230
Show file tree
Hide file tree
Showing 9 changed files with 234 additions and 111 deletions.
76 changes: 53 additions & 23 deletions ionit
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import yaml
import ionit_plugin

DEFAULT_CONFIG = "/etc/ionit"
LOG_FORMAT = '%(asctime)s %(name)s %(levelname)s: %(message)s'
LOG_FORMAT = "%(asctime)s %(name)s %(levelname)s: %(message)s"
SCRIPT_NAME = "ionit"


Expand All @@ -55,6 +55,7 @@ def load_python_plugin(file_path, current_context):
if sys.version_info[:2] < (3, 5):
# Backwards compatibility for Debian jessie
import warnings # pragma: no cover, pylint: disable=import-outside-toplevel

with warnings.catch_warnings(): # pragma: no cover
warnings.simplefilter("ignore")
import imp # pylint: disable=import-outside-toplevel
Expand All @@ -80,9 +81,11 @@ def load_python_plugin(file_path, current_context):
raise PythonModuleException() from error
context.update(new_context)
elif not context:
logger.warning("Python module '%s' does neither define a collect_context function, "
"nor export functions (using the ionit_plugin.function decorator).",
file_path)
logger.warning(
"Python module '%s' does neither define a collect_context function, "
"nor export functions (using the ionit_plugin.function decorator).",
file_path,
)

return context

Expand Down Expand Up @@ -127,8 +130,11 @@ def collect_context(paths):
with open(file) as config_file:
file_context = yaml.load(config_file)
else:
logger.info("Skipping configuration file '%s', because it does not end with "
"'.json', '.py', or '.yaml'.", file)
logger.info(
"Skipping configuration file '%s', "
"because it does not end with '.json', '.py', or '.yaml'.",
file,
)
continue
except PythonModuleException:
failures += 1
Expand All @@ -145,8 +151,7 @@ def collect_context(paths):
context.update(file_context)
except (TypeError, ValueError) as error:
logger.debug("Current context: %s", context)
logger.error("Failed to update context with content from '%s': %s",
file, error)
logger.error("Failed to update context with content from '%s': %s", file, error)
failures += 1
continue

Expand All @@ -160,9 +165,11 @@ def render_templates(template_dir, context, template_extension):
logger = logging.getLogger(SCRIPT_NAME)
logger.debug("Searching in directory '%s' for Jinja templates...", template_dir)
failures = 0
env = jinja2.Environment(keep_trailing_newline=True,
loader=jinja2.FileSystemLoader(template_dir),
undefined=jinja2.StrictUndefined)
env = jinja2.Environment(
keep_trailing_newline=True,
loader=jinja2.FileSystemLoader(template_dir),
undefined=jinja2.StrictUndefined,
)
for name in env.list_templates(extensions=[template_extension]):
try:
template = env.get_template(name)
Expand Down Expand Up @@ -196,18 +203,41 @@ def render_templates(template_dir, context, template_extension):
def main(argv):
"""Main function with argument parsing"""
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--config", action="append",
help="Configuration directory/file containing context for rendering "
"(default: %s)" % (DEFAULT_CONFIG,))
parser.add_argument("-t", "--templates", default="/etc",
help="Directory to search for Jinja templates (default: %(default)s)")
parser.add_argument("-e", "--template-extension", default="jinja",
help="Extension to look for in template directory (default: %(default)s)")
parser.add_argument("--debug", dest="log_level", help="Print debug output",
action="store_const", const=logging.DEBUG, default=logging.INFO)
parser.add_argument("-q", "--quiet", dest="log_level",
help="Decrease output verbosity to warnings and errors",
action="store_const", const=logging.WARNING)
parser.add_argument(
"-c",
"--config",
action="append",
help="Configuration directory/file containing context for rendering (default: %s)"
% (DEFAULT_CONFIG,),
)
parser.add_argument(
"-t",
"--templates",
default="/etc",
help="Directory to search for Jinja templates (default: %(default)s)",
)
parser.add_argument(
"-e",
"--template-extension",
default="jinja",
help="Extension to look for in template directory (default: %(default)s)",
)
parser.add_argument(
"--debug",
dest="log_level",
help="Print debug output",
action="store_const",
const=logging.DEBUG,
default=logging.INFO,
)
parser.add_argument(
"-q",
"--quiet",
dest="log_level",
help="Decrease output verbosity to warnings and errors",
action="store_const",
const=logging.WARNING,
)
args = parser.parse_args(argv)
if args.config is None:
args.config = [DEFAULT_CONFIG]
Expand Down
5 changes: 3 additions & 2 deletions ionit_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@
import logging


class FunctionCollector():
class FunctionCollector:
"""Collect functions for the Jinja renderer"""

functions = {}

def __new__(cls):
# Singleton
if not hasattr(cls, 'instance') or not cls.instance:
if not hasattr(cls, "instance") or not cls.instance:
cls.instance = super().__new__(cls)
return cls.instance

Expand Down
5 changes: 3 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,14 @@ def systemd_unit_path():
"ionit is a simple and small configuration templating tool. It collects a context and "
"renders Jinja templates in a given directory. The context can be either static JSON "
"or YAML files or dynamic Python files. Python files can also define functions passed "
"through to the rendering."),
"through to the rendering."
),
author="Benjamin Drung",
author_email="[email protected]",
url="https://github.com/bdrung/ionit",
license="ISC",
install_requires=["jinja2"],
scripts=["ionit"],
py_modules=["ionit_plugin"],
data_files=[(systemd_unit_path(), ['ionit.service'])]
data_files=[(systemd_unit_path(), ["ionit.service"])],
)
3 changes: 2 additions & 1 deletion tests/mock_open.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@

class NotMocked(Exception):
"""Raised when a file was opened which was not mocked"""

def __init__(self, filename):
super().__init__("The file %s was opened, but not mocked." % filename)
self.filename = filename
Expand Down Expand Up @@ -78,7 +79,7 @@ def mock_file(*args):
open_files.add(file_.name)
return file_

mocked_file = unittest.mock.patch('builtins.open', mock_file)
mocked_file = unittest.mock.patch("builtins.open", mock_file)
mocked_file.start()
try:
yield
Expand Down
6 changes: 6 additions & 0 deletions tests/pylint.conf
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ disable=bad-option-value,fixme,locally-enabled,locally-disabled
reports=no


[SIMILARITIES]

# Minimum lines number of a similarity.
min-similarity-lines=5


[FORMAT]

# Maximum number of characters on a single line.
Expand Down
19 changes: 13 additions & 6 deletions tests/test_flake8.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,25 @@ def test_flake8(self):
cmd = [sys.executable, "-m", "flake8", "--max-line-length=99"] + get_source_files()
if unittest_verbosity() >= 2:
sys.stderr.write("Running following command:\n{}\n".format(" ".join(cmd)))
process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, close_fds=True)
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True
)

out, err = process.communicate()
if process.returncode != 0: # pragma: no cover
msgs = []
if err:
msgs.append("flake8 exited with code {} and has unexpected output on stderr:\n{}"
.format(process.returncode, err.decode().rstrip()))
msgs.append(
"flake8 exited with code {} and has unexpected output on stderr:\n{}".format(
process.returncode, err.decode().rstrip()
)
)
if out:
msgs.append("flake8 found issues:\n{}".format(out.decode().rstrip()))
if not msgs:
msgs.append("flake8 exited with code {} and has no output on stdout or stderr."
.format(process.returncode))
msgs.append(
"flake8 exited with code {} and has no output on stdout or stderr.".format(
process.returncode
)
)
self.fail("\n".join(msgs))
Loading

0 comments on commit 6ece230

Please sign in to comment.