File: config.py

package info (click to toggle)
setools 4.6.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,600 kB
  • sloc: python: 24,485; makefile: 14
file content (67 lines) | stat: -rw-r--r-- 1,883 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# Copyright 2019, Chris PeBenito <pebenito@ieee.org>
#
# SPDX-License-Identifier: LGPL-2.1-only
#
#

import os
import logging
import configparser
import threading
import typing

#
# Configfile constants
#
APOLCONFIG: typing.Final[str] = "~/.config/setools/apol.conf"
HELP_SECTION: typing.Final[str] = "Help"
HELP_PGM: typing.Final[str] = "assistant"
DEFAULT_HELP_PGM: typing.Final[str] = "/usr/bin/assistant"


class ApolConfig:

    """Apol configuration file."""

    def __init__(self) -> None:
        self.log: typing.Final = logging.getLogger(__name__)
        self._lock = threading.Lock()
        self.path: typing.Final = os.path.expanduser(APOLCONFIG)

        self._config = configparser.ConfigParser()
        save = False

        if not self._config.read((self.path,)):
            save = True

        if not self._config.has_section(HELP_SECTION):
            self._config.add_section(HELP_SECTION)
            self._config.set(HELP_SECTION, HELP_PGM, DEFAULT_HELP_PGM)
            save = True

        if save:
            self.save()

    def save(self) -> None:
        """Save configuration file."""
        with self._lock:
            try:
                os.makedirs(os.path.dirname(self.path), mode=0o755, exist_ok=True)

                with open(self.path, "w") as fd:
                    self._config.write(fd)

            except Exception:
                self.log.critical(f"Failed to save configuration file \"{self.path}\"")
                self.log.debug("Backtrace", exc_info=True)

    @property
    def assistant(self) -> str:
        """Return the help program executable path."""
        with self._lock:
            return self._config.get(HELP_SECTION, HELP_PGM, fallback=DEFAULT_HELP_PGM)

    @assistant.setter
    def assistant(self, value: str) -> None:
        with self._lock:
            self._config.set(HELP_SECTION, HELP_PGM, value)