CI: Use latest actions and reusable workflows
[releng/lftools.git] / lftools / config.py
1 # -*- coding: utf-8 -*-
2 # SPDX-License-Identifier: EPL-1.0
3 ##############################################################################
4 # Copyright (c) 2018 The Linux Foundation and others.
5 #
6 # All rights reserved. This program and the accompanying materials
7 # are made available under the terms of the Eclipse Public License v1.0
8 # which accompanies this distribution, and is available at
9 # http://www.eclipse.org/legal/epl-v10.html
10 ##############################################################################
11 """Configuration subsystem for lftools."""
12 from __future__ import annotations
13
14 import logging
15 import os.path
16 import sys
17 from configparser import ConfigParser, NoOptionError, NoSectionError
18 from typing import List, Optional
19
20 from xdg import XDG_CONFIG_HOME
21
22 log: logging.Logger = logging.getLogger(__name__)
23
24 LFTOOLS_CONFIG_FILE: str = os.path.join(XDG_CONFIG_HOME, "lftools", "lftools.ini")
25
26
27 def get_config() -> ConfigParser:
28     """Get the config object."""
29     config: ConfigParser = ConfigParser()  # noqa
30     config.read(LFTOOLS_CONFIG_FILE)
31     return config
32
33
34 def has_section(section: str) -> bool:
35     """Get a configuration from a section."""
36     config = get_config()
37     return config.has_section(section)
38
39
40 def get_setting(section: str, option: Optional[str] = None) -> str | List[str]:
41     """Get a configuration from a section."""
42     sys.tracebacklimit = 0
43     config: ConfigParser = get_config()
44
45     if option:
46         try:
47             return config.get(section, option)
48         except (NoOptionError, NoSectionError) as e:
49             raise e
50
51     else:
52         try:
53             return config.options(section)
54         except NoSectionError as e:
55             raise e
56
57
58 def set_setting(section: str, option: str, value: str) -> None:
59     """Save a configuration setting to config file."""
60     config: ConfigParser = get_config()
61     config.set(section, option, value)
62
63     with open(LFTOOLS_CONFIG_FILE, "w") as configfile:
64         config.write(configfile)