From 19375c42643b2c5ca2c494c760d7cc7887b95608 Mon Sep 17 00:00:00 2001 From: Edoardo Putti Date: Fri, 20 Jul 2018 12:24:34 +0200 Subject: [PATCH] draft for loading external converters, references #112 --- netjsonconfig/backends/base/backend.py | 16 ++++++++++++++++ netjsonconfig/backends/openvpn/openvpn.py | 2 +- netjsonconfig/backends/openwrt/openwrt.py | 2 +- 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/netjsonconfig/backends/base/backend.py b/netjsonconfig/backends/base/backend.py index 892c67cba..cbf120c51 100644 --- a/netjsonconfig/backends/base/backend.py +++ b/netjsonconfig/backends/base/backend.py @@ -4,6 +4,7 @@ from collections import OrderedDict from copy import deepcopy from io import BytesIO +from pkg_resources import iter_entry_points import six from jsonschema import FormatChecker, validate @@ -21,6 +22,7 @@ class BaseBackend(object): schema = None FILE_SECTION_DELIMITER = '# ---------- files ---------- #' list_identifiers = [] + _converters = [] def __init__(self, config=None, native=None, templates=None, context=None): """ @@ -49,6 +51,20 @@ def __init__(self, config=None, native=None, templates=None, context=None): raise ValueError('Expecting either config or native argument to be ' 'passed during the initialization of the backend') + @property + def converters(self): + converters = [] + entry_key = 'netjsonconfig.{}.converter'.format(self.__class__.__name__) + for entry_point in iter_entry_points(entry_key): + try: + converters.append(entry_point.load()) + except ImportError as e: # noqa + # TODO: some error handling here + continue + + return self._converters + converters + + def _load(self, config): """ Loads config from string or dict diff --git a/netjsonconfig/backends/openvpn/openvpn.py b/netjsonconfig/backends/openvpn/openvpn.py index 4145ce5e9..46a1b9b6e 100644 --- a/netjsonconfig/backends/openvpn/openvpn.py +++ b/netjsonconfig/backends/openvpn/openvpn.py @@ -11,7 +11,7 @@ class OpenVpn(BaseBackend): OpenVPN 2.x Configuration Backend """ schema = schema - converters = [converters.OpenVpn] + _converters = [converters.OpenVpn] parser = OpenVpnParser renderer = OpenVpnRenderer list_identifiers = ['name'] diff --git a/netjsonconfig/backends/openwrt/openwrt.py b/netjsonconfig/backends/openwrt/openwrt.py index 0d18d91ff..01e66e798 100644 --- a/netjsonconfig/backends/openwrt/openwrt.py +++ b/netjsonconfig/backends/openwrt/openwrt.py @@ -10,7 +10,7 @@ class OpenWrt(BaseBackend): OpenWRT / LEDE Configuration Backend """ schema = schema - converters = [ + _converters = [ converters.General, converters.Ntp, converters.Led,