Passed
Pull Request — master (#560)
by Osma
05:47
created

annif.config.parse_config()   A

Complexity

Conditions 4

Size

Total Lines 13
Code Lines 9

Duplication

Lines 13
Ratio 100 %

Importance

Changes 0
Metric Value
cc 4
eloc 9
nop 1
dl 13
loc 13
rs 9.95
c 0
b 0
f 0
1
"""Configuration file handling"""
2
3
4
import os.path
5
import configparser
6
import tomli
7
import annif
8
import annif.util
9
from annif.exception import ConfigurationException
10
11
12
logger = annif.logger
13
14
15 View Code Duplication
class AnnifConfigCFG:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
16
    """Class for reading configuration in CFG/INI format"""
17
18
    def __init__(self, filename):
19
        self._config = configparser.ConfigParser()
20
        self._config.optionxform = annif.util.identity
21
        with open(filename, encoding='utf-8-sig') as projf:
22
            try:
23
                logger.debug(
24
                    f"Reading configuration file {filename} in CFG format")
25
                self._config.read_file(projf)
26
            except (configparser.DuplicateOptionError,
27
                    configparser.DuplicateSectionError) as err:
28
                raise ConfigurationException(err)
29
30
    @property
31
    def project_ids(self):
32
        return self._config.sections()
33
34
    def __getitem__(self, key):
35
        return self._config[key]
36
37
38 View Code Duplication
class AnnifConfigTOML:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
39
    """Class for reading configuration in TOML format"""
40
41
    def __init__(self, filename):
42
        with open(filename, "rb") as projf:
43
            try:
44
                logger.debug(
45
                    f"Reading configuration file {filename} in TOML format")
46
                self._config = tomli.load(projf)
47
            except tomli.TOMLDecodeError as err:
48
                raise ConfigurationException(
49
                    f"Parsing TOML file '{filename}' failed: {err}")
50
51
    @property
52
    def project_ids(self):
53
        return self._config.keys()
54
55
    def __getitem__(self, key):
56
        return self._config[key]
57
58
59
def check_config(projects_file):
60
    if os.path.exists(projects_file):
61
        return projects_file
62
    else:
63
        logger.warning(
64
            f'Project configuration file "{projects_file}" is ' +
65
            'missing. Please provide one. ' +
66
            'You can set the path to the project configuration ' +
67
            'file using the ANNIF_PROJECTS environment ' +
68
            'variable or the command-line option "--projects".')
69
        return None
70
71
72
def find_config():
73
    for filename in ('projects.cfg', 'projects.toml'):
74
        if os.path.exists(filename):
75
            return filename
76
77
    logger.warning(
78
        'Could not find project configuration file ' +
79
        '"projects.cfg" or "projects.toml". ' +
80
        'You can set the path to the project configuration ' +
81
        'file using the ANNIF_PROJECTS environment ' +
82
        'variable or the command-line option "--projects".')
83
    return None
84
85
86 View Code Duplication
def parse_config(projects_file):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
87
    if projects_file:
88
        filename = check_config(projects_file)
89
    else:
90
        filename = find_config()
91
92
    if not filename:  # not found
93
        return None
94
95
    if filename.endswith('.toml'):  # TOML format
96
        return AnnifConfigTOML(filename)
97
    else:  # classic CFG/INI style format
98
        return AnnifConfigCFG(filename)
99