1
0
Эх сурвалжийг харах

configuration moved to own module, throws own Exception "InvalidConfig"

twall 11 жил өмнө
parent
commit
6869cfcbeb

+ 3 - 71
nsist/__init__.py

@@ -6,7 +6,6 @@ import os
 import shutil
 from subprocess import check_output, call
 import sys
-import configparser
 
 PY2 = sys.version_info[0] == 2
 
@@ -24,6 +23,7 @@ else:
 
 from .copymodules import copy_modules
 from .nsiswriter import NSISFileWriter
+from . import configreader
 
 pjoin = os.path.join
 logger = logging.getLogger(__name__)
@@ -252,74 +252,6 @@ def read_shortcuts_config(cfg):
     
     return shortcuts
 
-def read_and_verify_config_file(config_file):
-    cfg = configparser.ConfigParser()
-    cfg.read(config_file)
-    # contains all configuration sections and subsections
-    # the subsections are a tuple with their name and a boolean, which
-    # tells us whether the option is mandatory
-    valid_config_sections = {
-        'Application': [
-            ('name', True),
-            ('version', True),
-            ('entry_point', True),
-            ('script', False),
-            ('icon', False),
-            ('console', False),
-        ],
-        'Build': [
-            ('directory', False),
-            ('installer_name', False),
-            ('nsi_template', False),
-        ],
-        'Include': [
-            ('packages', False),
-            ('files', False),
-        ],
-        'Python': [
-            ('version', True),
-            ('bitness', False),
-        ],
-    }
-    # check for invalid sections and subsections
-    for section in cfg:
-        # check section names
-        section_name = str(section)
-        is_valid_section_name = section_name in valid_config_sections.keys()
-        if section_name == 'DEFAULT':
-            # DEFAULT is always inside the config, so just jump over it
-            continue
-        if not is_valid_section_name:
-            err_msg = ("{0} is not a valid section header. Must "
-                       "be one of these: {1}").format(
-                       section_name, ', '.join(valid_section_headers))
-            raise NameError(err_msg)
-        # check subsection names
-        for subsection in cfg[section_name]:
-            subsection_name = str(subsection)
-            subsection_names = [s[0] for s in valid_config_sections[section_name]]
-            is_valid_subsection = subsection_name in subsection_names
-            if not is_valid_subsection:
-                err_msg = ("'{0}' is not a valid subsection name for '{1}'. Must "
-                           "be one of these: {2}").format(
-                            subsection_name,
-                            section_name,
-                            ', '.join(subsection_names))
-                raise NameError(err_msg)
-    # check mandatory sections
-    for section_name, subsection_list in valid_config_sections.items():
-        for subsection_name, mandatory in subsection_list:
-            if mandatory:
-                try:
-                    cfg[section_name][subsection_name]
-                except KeyError:
-                    err_msg = ("The section '{0}' must contain a "
-                               "subsection '{1}'!").format(
-                                section_name,
-                                subsection_name)
-                    raise NameError(err_msg)
-    return cfg
-
 def main(argv=None):
     """Make an installer from the command line.
     
@@ -339,8 +271,8 @@ def main(argv=None):
         os.chdir(dirname)
     
     try:
-        cfg = read_and_verify_config_file(config_file)
-    except NameError as e:
+        cfg = configreader.read_and_validate(config_file)
+    except configreader.InvalidConfig as e:
         logger.error('Error parsing configuration file:')
         logger.error(str(e))
         sys.exit(1)

+ 76 - 0
nsist/configreader.py

@@ -0,0 +1,76 @@
+#!/usr/bin/python3
+
+import configparser
+
+# contains all configuration sections and subsections
+# the subsections are a tuple with their name and a boolean, which
+# tells us whether the option is mandatory
+VALID_CONFIG_SECTIONS = {
+    'Application': [
+        ('name', True),
+        ('version', True),
+        ('entry_point', True),
+        ('script', False),
+        ('icon', False),
+        ('console', False),
+    ],
+    'Build': [
+        ('directory', False),
+        ('installer_name', False),
+        ('nsi_template', False),
+    ],
+    'Include': [
+        ('packages', False),
+        ('files', False),
+    ],
+    'Python': [
+        ('version', True),
+        ('bitness', False),
+    ],
+}
+
+class InvalidConfig(ValueError):
+    pass
+
+def read_and_validate(config_file):
+    cfg = configparser.ConfigParser()
+    cfg.read(config_file)
+    # check mandatory sections
+    for section_name, subsection_list in VALID_CONFIG_SECTIONS.items():
+        for subsection_name, mandatory in subsection_list:
+            if mandatory:
+                try:
+                    cfg[section_name][subsection_name]
+                except KeyError:
+                    err_msg = ("The section '{0}' must contain a "
+                               "subsection '{1}'!").format(
+                                section_name,
+                                subsection_name)
+                    raise InvalidConfig(err_msg)
+
+    # check for invalid sections and subsections
+    for section in cfg:
+        # check section names
+        section_name = str(section)
+        is_valid_section_name = section_name in VALID_CONFIG_SECTIONS.keys()
+        if section_name == 'DEFAULT':
+            # DEFAULT is always inside the config, so just jump over it
+            continue
+        if not is_valid_section_name:
+            err_msg = ("{0} is not a valid section header. Must "
+                       "be one of these: {1}").format(
+                       section_name, ', '.join(valid_section_headers))
+            raise InvalidConfig(err_msg)
+        # check subsection names
+        for subsection in cfg[section_name]:
+            subsection_name = str(subsection)
+            subsection_names = [s[0] for s in VALID_CONFIG_SECTIONS[section_name]]
+            is_valid_subsection = subsection_name in subsection_names
+            if not is_valid_subsection:
+                err_msg = ("'{0}' is not a valid subsection name for '{1}'. Must "
+                           "be one of these: {2}").format(
+                            subsection_name,
+                            section_name,
+                            ', '.join(subsection_names))
+                raise InvalidConfig(err_msg)
+    return cfg

+ 11 - 10
nsist/tests/test_configuration_validator.py

@@ -1,29 +1,30 @@
 from nose.tools import *
 import os
-from nsist import read_and_verify_config_file
+from .. import configreader
+import configparser
 
 DATA_FILES = os.path.join(os.path.dirname(__file__), 'data_files')
 
 def test_valid_config():
     configfile = os.path.join(DATA_FILES, 'valid_config.cfg')
-    read_and_verify_config_file(configfile)
+    configreader.read_and_validate(configfile)
 
-@raises(NameError)
+@raises(configreader.InvalidConfig)
 def test_invalid_config_keys():
     configfile = os.path.join(DATA_FILES, 'invalid_config_keys.cfg')
-    read_and_verify_config_file(configfile)
+    configreader.read_and_validate(configfile)
 
-@raises(NameError)
+@raises(configreader.InvalidConfig)
 def test_invalid_config_subsection():
     configfile = os.path.join(DATA_FILES, 'invalid_config_subsection.cfg')
-    read_and_verify_config_file(configfile)
+    configreader.read_and_validate(configfile)
 
-@raises(NameError)
+@raises(configreader.InvalidConfig)
 def test_missing_config_subsection():
     configfile = os.path.join(DATA_FILES, 'missing_config_subsection.cfg')
-    read_and_verify_config_file(configfile)
+    configreader.read_and_validate(configfile)
 
-@raises(Exception)
+@raises(configparser.Error)
 def test_invalid_config_file():
     configfile = os.path.join(DATA_FILES, 'not_a_config.cfg')
-    read_and_verify_config_file(configfile)
+    configreader.read_and_validate(configfile)