From c4827f8ba51e28f35cfa12de820f01fae40c05e8 Mon Sep 17 00:00:00 2001
From: ulif <uli@gnufix.de>
Date: Mon, 9 May 2016 16:50:07 +0200
Subject: [PATCH] Allow a `section` parameter for `get_config_dict()`.

In config files we normally lookup a ``[diceware]`` section.

For plugins, however, it might be helpful to be able to parse also
other sections. Together with the new `defaults_dict` argument
they could implement their own set of options more easily.
---
 diceware/config.py   | 15 ++++++++-------
 tests/test_config.py |  7 +++++++
 2 files changed, 15 insertions(+), 7 deletions(-)

diff --git a/diceware/config.py b/diceware/config.py
index 4d4cddd..36af4d0 100644
--- a/diceware/config.py
+++ b/diceware/config.py
@@ -61,11 +61,12 @@ def get_configparser(path_list=None):
     return found, parser
 
 
-def get_config_dict(path_list=None, defaults_dict=OPTIONS_DEFAULTS):
+def get_config_dict(
+        path_list=None, defaults_dict=OPTIONS_DEFAULTS, section="diceware"):
     """Get config values found in files from `path_list`.
 
-    Read files in `path_list` config files and return option valus as
-    regular dictonary.
+    Read files in `path_list` config files and return option values from
+    section `section` as regular dictonary.
 
     We only accept values for which a default exists in
     `defaults_dict`. If `defaults_dict` is ``None`` we use
@@ -80,12 +81,12 @@ def get_config_dict(path_list=None, defaults_dict=OPTIONS_DEFAULTS):
     result = dict(defaults_dict)
     found, parser = get_configparser(path_list)
     for key, val in defaults_dict.items():
-        if not parser.has_option('diceware', key):
+        if not parser.has_option(section, key):
             continue
         if isinstance(val, bool):
-            result[key] = parser.getboolean("diceware", key)
+            result[key] = parser.getboolean(section, key)
         elif isinstance(val, int):
-            result[key] = parser.getint("diceware", key)
+            result[key] = parser.getint(section, key)
         else:
-            result[key] = parser.get("diceware", key).strip("\"'")
+            result[key] = parser.get(section, key).strip("\"'")
     return result
diff --git a/tests/test_config.py b/tests/test_config.py
index 7f3fd2d..d7aadd0 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -84,6 +84,13 @@ class TestGetConfigDict(object):
         assert conf_dict == dict(num=42)
         assert conf_dict is not custom_defaults
 
+    def test_get_config_dict_arg_section(self, home_dir):
+        # we can set the section name to look for in config files.
+        config_file = home_dir / ".diceware.ini"
+        config_file.write("[diceware]\nnum=4\n[foo]\nnum=5\n[bar]\nnum=6\n")
+        conf_dict = get_config_dict(section='foo')
+        assert conf_dict['num'] == 5
+
     def test_get_config_dict_int(self, home_dir):
         # integer values are interpolated correctly
         config_file = home_dir / ".diceware.ini"
-- 
GitLab