rkt-config-lib 1.3.0__tar.gz → 2.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.4
2
+ Name: rkt_config_lib
3
+ Version: 2.0.0
4
+ Summary: RootKit custom PyYaml Lib
5
+ Author-email: RootKit <rootkit@rootkit-lab.org>
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Operating System :: OS Independent
9
+ Requires-Python: >=3.7
10
+ Requires-Dist: PyYaml>=6.0.1
11
+ Requires-Dist: rkt_tool_lib
12
+ Requires-Dist: rkt_logger_lib
@@ -0,0 +1,22 @@
1
+ # rkt_config_lib
2
+
3
+ Centralized Configuration Management wrapper around PyYaml.
4
+
5
+ ## Features
6
+ - **Singleton Pattern**: Ensures a single configuration state across your application.
7
+ - **Auto-Loading**: Automatically scans and loads all YAML files in a `config/` directory.
8
+ - **Safe Loading**: Uses `yaml.safe_load` by default to prevent arbitrary code execution vulnerabilities.
9
+ - **Integrated Logging**: Logs loading operations via `rkt_logger_lib`.
10
+
11
+ ## Usage
12
+
13
+ ```python
14
+ from config import Config
15
+
16
+ conf = Config()
17
+ # Loads all .yml/.yaml files from ./config/ directory
18
+ conf.get_data()
19
+
20
+ # Access data (filename becomes the key)
21
+ my_settings = conf.data.get("settings")
22
+ ```
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "rkt_config_lib"
7
+ version = "2.0.0"
8
+ description = "RootKit custom PyYaml Lib"
9
+ authors = [
10
+ { name="RootKit", email="rootkit@rootkit-lab.org" },
11
+ ]
12
+ classifiers = [
13
+ "Programming Language :: Python :: 3",
14
+ "License :: OSI Approved :: MIT License",
15
+ "Operating System :: OS Independent",
16
+ ]
17
+ requires-python = ">=3.7"
18
+ dependencies = [
19
+ "PyYaml>=6.0.1",
20
+ "rkt_tool_lib",
21
+ "rkt_logger_lib",
22
+ ]
23
+
24
+ [tool.setuptools.packages.find]
25
+ where = ["src"]
@@ -0,0 +1 @@
1
+ from .config import Config
@@ -0,0 +1,59 @@
1
+ import os
2
+ from typing import Any
3
+
4
+ import yaml
5
+
6
+ from logger import Logger
7
+ from tool import Singleton, Tool
8
+
9
+
10
+ class Config(metaclass=Singleton): # type: ignore[metaclass]
11
+ """
12
+ Configuration manager wrapping PyYaml.
13
+
14
+ This class handles the loading of YAML configuration files from a specific directory.
15
+ It implements the Singleton pattern to ensure centralized configuration management.
16
+ """
17
+
18
+ __slots__ = ["_me", "_logger", "_tool", "_skills_file", "data"]
19
+
20
+ def __init__(self) -> None:
21
+ self._me = self.__class__.__name__
22
+ self._logger = Logger(caller_class=self._me)
23
+ self._logger.set_logger(caller_class=self._me)
24
+ self._tool = Tool()
25
+ self.data: dict[str, Any] = {}
26
+
27
+ def get_data(self, needed_file: str = "", _config_dir: str = "config", create_if_not_exist: bool = False) -> None:
28
+ """
29
+ Load configuration files from the config directory.
30
+
31
+ It scans the directory for YAML files and loads them into `self.data`.
32
+
33
+ Args:
34
+ needed_file (str, optional): A specific file to load. If empty, loads all YAML files in the directory.
35
+ Defaults to "".
36
+ _config_dir (str, optional): Name of the configuration directory. Defaults to "config".
37
+ create_if_not_exist (bool, optional): Create the config directory if it doesn't exist. Defaults to False.
38
+ """
39
+ config_dir = self._tool.get_dir(_config_dir)
40
+
41
+ if (not config_dir or not os.path.exists(config_dir)) and create_if_not_exist:
42
+ os.makedirs(_config_dir, exist_ok=True)
43
+ config_dir = self._tool.formatted_from_os(os.path.abspath(_config_dir))
44
+
45
+ if needed_file:
46
+ filename = os.path.basename(needed_file).split(".")[0]
47
+ with open(f"{config_dir}{needed_file}", encoding="utf8") as nf:
48
+ self._logger.add(level="info", caller=self._me, message=f"Load '{filename}' file ...")
49
+ self.data[filename] = yaml.safe_load(nf)
50
+ else:
51
+ for file in os.listdir(config_dir):
52
+ try:
53
+ (filename, ext) = os.path.basename(file).split(".")
54
+ except ValueError:
55
+ continue
56
+ if ext in ["yml", "yaml"] and filename not in self.data.keys():
57
+ with open(f"{config_dir}{file}", encoding="utf8") as f:
58
+ self._logger.add(level="info", caller=self._me, message=f"Load '{filename}' file ...")
59
+ self.data[filename] = yaml.safe_load(f)
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.4
2
+ Name: rkt_config_lib
3
+ Version: 2.0.0
4
+ Summary: RootKit custom PyYaml Lib
5
+ Author-email: RootKit <rootkit@rootkit-lab.org>
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Operating System :: OS Independent
9
+ Requires-Python: >=3.7
10
+ Requires-Dist: PyYaml>=6.0.1
11
+ Requires-Dist: rkt_tool_lib
12
+ Requires-Dist: rkt_logger_lib
@@ -0,0 +1,10 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/config/__init__.py
4
+ src/config/config.py
5
+ src/rkt_config_lib.egg-info/PKG-INFO
6
+ src/rkt_config_lib.egg-info/SOURCES.txt
7
+ src/rkt_config_lib.egg-info/dependency_links.txt
8
+ src/rkt_config_lib.egg-info/requires.txt
9
+ src/rkt_config_lib.egg-info/top_level.txt
10
+ tests/test_config.py
@@ -1,3 +1,3 @@
1
- PyYaml
1
+ PyYaml>=6.0.1
2
2
  rkt_tool_lib
3
3
  rkt_logger_lib
@@ -0,0 +1,66 @@
1
+ import os
2
+ import shutil
3
+ from typing import Any, Optional
4
+ from unittest import TestCase
5
+ from unittest.mock import patch
6
+
7
+ from yaml.scanner import ScannerError
8
+
9
+ from config import Config
10
+ from tool import Tool
11
+
12
+
13
+ class TestConfig(TestCase):
14
+ def get_dir_side_effect(self, folder: str, root: "Optional[str]" = None) -> "Optional[str]":
15
+ if folder in ["valid_config", "dummy_config", "missing_folder"]:
16
+ return str(Tool.formatted_from_os(os.path.join(os.path.dirname(__file__), "resources", folder)))
17
+ # Use the original method from the class, passing a new instance or self if relevant
18
+ # Accessing the original method requires unpatching or saving it.
19
+ # Simpler: just return None or duplicate logic for now since we don't expect other calls.
20
+ return None
21
+
22
+ @patch("tool.Tool.get_dir")
23
+ def test_get_data(self, mock_get_dir: "Any") -> None:
24
+ mock_get_dir.side_effect = self.get_dir_side_effect
25
+ config = Config()
26
+ config.data.clear()
27
+ config.get_data(_config_dir="valid_config")
28
+
29
+ assert config.data == {
30
+ "valid_config": {
31
+ "key1": {"sub_key": "value", "sub_key2": "value", "sub_key3": "value", "sub_key4": "value"}
32
+ }
33
+ }
34
+
35
+ @patch("tool.Tool.get_dir")
36
+ def test_get_data_dummy_data(self, mock_get_dir: "Any") -> None:
37
+ mock_get_dir.side_effect = self.get_dir_side_effect
38
+ config = Config()
39
+ config.data.clear()
40
+ try:
41
+ config.get_data(_config_dir="dummy_config")
42
+ self.fail("ScannerError expected here!")
43
+ except ScannerError:
44
+ assert config.data == {}
45
+
46
+ @patch("tool.Tool.get_dir")
47
+ def test_get_data_dummy_folder(self, mock_get_dir: "Any") -> None:
48
+ mock_get_dir.side_effect = self.get_dir_side_effect
49
+ config = Config()
50
+ config.data.clear()
51
+ config.get_data(_config_dir="missing_folder", create_if_not_exist=True)
52
+ assert os.path.exists("missing_folder")
53
+ shutil.rmtree("missing_folder")
54
+
55
+ @patch("tool.Tool.get_dir")
56
+ def test_get_data_from_specific_file(self, mock_get_dir: "Any") -> None:
57
+ mock_get_dir.side_effect = self.get_dir_side_effect
58
+ config = Config()
59
+ config.data.clear()
60
+ config.get_data(_config_dir="valid_config", needed_file="valid_config.yml")
61
+
62
+ assert config.data == {
63
+ "valid_config": {
64
+ "key1": {"sub_key": "value", "sub_key2": "value", "sub_key3": "value", "sub_key4": "value"}
65
+ }
66
+ }
@@ -1,21 +0,0 @@
1
- The MIT License (MIT)
2
-
3
- Copyright (c) 2016 Dabo Ross
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
@@ -1,98 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: rkt_config_lib
3
- Version: 1.3.0
4
- Summary: RootKit custom PyYaml Lib
5
- Home-page: UNKNOWN
6
- Author: RootKit
7
- Author-email: rootkit@rootkit-lab.org
8
- License: UNKNOWN
9
- Platform: UNKNOWN
10
- Classifier: Development Status :: 5 - Production/Stable
11
- Classifier: Intended Audience :: Developers
12
- Classifier: Intended Audience :: End Users/Desktop
13
- Classifier: Intended Audience :: Information Technology
14
- Classifier: License :: OSI Approved :: MIT License
15
- Classifier: Natural Language :: English
16
- Classifier: Natural Language :: French
17
- Classifier: Operating System :: OS Independent
18
- Classifier: Programming Language :: Python :: 3.7
19
- Classifier: Topic :: Utilities
20
- Requires-Python: >=3.7
21
- Description-Content-Type: text/markdown
22
- License-File: LICENSE
23
-
24
- # rkt_config_lib - Python library
25
-
26
- ![Package Version](https://badgen.net/badge/Package%20Version/latest%20-%201.3.0/green?scale=1.2)
27
-
28
- ![quality](https://sonarqube.tprc.ovh/api/project_badges/measure?project=python_rkt_lib_toolkit_AXqQ32evGCA0VuRY8SuD&metric=alert_status)
29
- ![reliability_rating](https://sonarqube.tprc.ovh/api/project_badges/measure?project=python_rkt_lib_toolkit_AXqQ32evGCA0VuRY8SuD&metric=reliability_rating)
30
- ![security_rating](https://sonarqube.tprc.ovh/api/project_badges/measure?project=python_rkt_lib_toolkit_AXqQ32evGCA0VuRY8SuD&metric=security_rating)
31
- ![vulnerabilities](https://sonarqube.tprc.ovh/api/project_badges/measure?project=python_rkt_lib_toolkit_AXqQ32evGCA0VuRY8SuD&metric=vulnerabilities)
32
- ![coverage](https://sonarqube.tprc.ovh/api/project_badges/measure?project=python_rkt_lib_toolkit_AXqQ32evGCA0VuRY8SuD&metric=coverage)
33
- ![maintainability](https://sonarqube.tprc.ovh/api/project_badges/measure?project=python_rkt_lib_toolkit_AXqQ32evGCA0VuRY8SuD&metric=sqale_rating)
34
-
35
- This Python library is based only on built-in Python libraries and one (1) non-build-in library : [PyYaml](https://pypi.org/project/PyYAML/)
36
-
37
- ##### Python Version 3.7.2
38
- ##### PyYaml Version 5.4.1 (Released Jan 20, 2021)
39
-
40
- ----
41
-
42
- ## What is Python?
43
- Python is an interpreted high-level general-purpose programming language. Python's design philosophy emphasizes code readability with its notable use of significant indentation. Its language constructs as well as its object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.
44
-
45
- [source](https://en.wikipedia.org/wiki/Python_(programming_language))
46
- ## What is PyYaml?
47
- YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python.
48
-
49
- PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object.
50
-
51
- PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistence.
52
-
53
- [source](https://pypi.org/project/PyYAML/)
54
- ## Libraries
55
- * Config: overlay of PyYaml library (read-only), use Tool and Logger library (rkt_tool_lib, rkt_logger_lib)
56
-
57
- ## Use it
58
- ### Install
59
- ```bash
60
- (venv) my_project> pip install rkt_config_lib [--index-url https://gitlab.tprc.ovh/api/v4/groups/python/-/packages/pypi]
61
- ```
62
- ### Example
63
- ```python
64
- from rkt_config_lib import Config
65
-
66
- c = Config()
67
-
68
- # by default search folder named "config" in root project folder
69
- # for load all yaml files
70
- c.get_data()
71
-
72
- print(f"{c.data}")
73
- ```
74
-
75
- ### Output (as file, sdtout or both)
76
- ```log
77
- 03/03/2022 16:44:09 :: [Logger] :: INFO :: Create logger for 'Config'
78
- 03/03/2022 16:44:09 :: [Logger] :: INFO :: add 'StreamHandler' in 'Config' logger
79
- 03/03/2022 16:44:09 :: [Logger] :: INFO :: add 'FileHandler' in 'Config' logger
80
- 03/03/2022 16:44:09 :: [Config] :: INFO :: Load 'database' file ...
81
- ```
82
- ```
83
- {'database': {'connect_id': {'dbms': 'mariadb'}}}
84
- ^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
85
- | |
86
- | data: file content
87
- file name without extension
88
- ```
89
-
90
- ## Contributing
91
-
92
- If you find this library useful here's how you can help:
93
-
94
- - Send a merge request with your kickass new features and bug fixes
95
- - Help new users with [issues](https://gitlab.tprc.ovh/python/rkt_lib_toolkit/-/issues) they may encounter
96
- - Support the development of this library and star this repo!
97
-
98
-
@@ -1,47 +0,0 @@
1
- import os
2
- import yaml
3
-
4
- from rkt_lib_toolkit.tool.Tool import Tool, Singleton
5
-
6
- from rkt_lib_toolkit.logger.Logger import Logger
7
-
8
-
9
- class Config(metaclass=Singleton):
10
- """
11
- Basic PyYaml wrapper
12
- add custom logger, list of file need to be load
13
-
14
- """
15
- __slots__ = ["_me", "_logger", "_tool", "_skills_file", "data"]
16
-
17
- def __init__(self) -> None:
18
- self._me = self.__class__.__name__
19
- self._logger = Logger(caller_class=self._me)
20
- self._logger.set_logger(caller_class=self._me)
21
- self._tool = Tool()
22
- self.data = {}
23
-
24
- def get_data(self, needed_file: str = "", config_dir: str = "config", create_if_not_exist: bool = False) -> None:
25
- """
26
- Load all file in 'config_dir' and get data in dict formatted as : {"basename_1": <VALUE_1>, ...}
27
- """
28
- config_dir = self._tool.get_dir(config_dir)
29
-
30
- if create_if_not_exist and not os.path.exists(config_dir):
31
- os.makedirs(config_dir, exist_ok=True)
32
-
33
- if needed_file:
34
- filename = os.path.basename(needed_file).split(".")[0]
35
- with open(f"{config_dir}{needed_file}", "r", encoding='utf8') as nf:
36
- self._logger.add(level="info", caller=self._me, message=f"Load '{filename}' file ...")
37
- self.data[filename] = yaml.load(nf, Loader=yaml.FullLoader)
38
- else:
39
- for file in os.listdir(config_dir):
40
- try:
41
- (filename, ext) = os.path.basename(file).split(".")
42
- except ValueError:
43
- continue
44
- if ext in ["yml", "yaml"] and filename not in self.data.keys():
45
- with open(f"{config_dir}{file}", "r", encoding='utf8') as f:
46
- self._logger.add(level="info", caller=self._me, message=f"Load '{filename}' file ...")
47
- self.data[filename] = yaml.load(f, Loader=yaml.FullLoader)
@@ -1 +0,0 @@
1
- from .Config import Config
@@ -1,98 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: rkt-config-lib
3
- Version: 1.3.0
4
- Summary: RootKit custom PyYaml Lib
5
- Home-page: UNKNOWN
6
- Author: RootKit
7
- Author-email: rootkit@rootkit-lab.org
8
- License: UNKNOWN
9
- Platform: UNKNOWN
10
- Classifier: Development Status :: 5 - Production/Stable
11
- Classifier: Intended Audience :: Developers
12
- Classifier: Intended Audience :: End Users/Desktop
13
- Classifier: Intended Audience :: Information Technology
14
- Classifier: License :: OSI Approved :: MIT License
15
- Classifier: Natural Language :: English
16
- Classifier: Natural Language :: French
17
- Classifier: Operating System :: OS Independent
18
- Classifier: Programming Language :: Python :: 3.7
19
- Classifier: Topic :: Utilities
20
- Requires-Python: >=3.7
21
- Description-Content-Type: text/markdown
22
- License-File: LICENSE
23
-
24
- # rkt_config_lib - Python library
25
-
26
- ![Package Version](https://badgen.net/badge/Package%20Version/latest%20-%201.3.0/green?scale=1.2)
27
-
28
- ![quality](https://sonarqube.tprc.ovh/api/project_badges/measure?project=python_rkt_lib_toolkit_AXqQ32evGCA0VuRY8SuD&metric=alert_status)
29
- ![reliability_rating](https://sonarqube.tprc.ovh/api/project_badges/measure?project=python_rkt_lib_toolkit_AXqQ32evGCA0VuRY8SuD&metric=reliability_rating)
30
- ![security_rating](https://sonarqube.tprc.ovh/api/project_badges/measure?project=python_rkt_lib_toolkit_AXqQ32evGCA0VuRY8SuD&metric=security_rating)
31
- ![vulnerabilities](https://sonarqube.tprc.ovh/api/project_badges/measure?project=python_rkt_lib_toolkit_AXqQ32evGCA0VuRY8SuD&metric=vulnerabilities)
32
- ![coverage](https://sonarqube.tprc.ovh/api/project_badges/measure?project=python_rkt_lib_toolkit_AXqQ32evGCA0VuRY8SuD&metric=coverage)
33
- ![maintainability](https://sonarqube.tprc.ovh/api/project_badges/measure?project=python_rkt_lib_toolkit_AXqQ32evGCA0VuRY8SuD&metric=sqale_rating)
34
-
35
- This Python library is based only on built-in Python libraries and one (1) non-build-in library : [PyYaml](https://pypi.org/project/PyYAML/)
36
-
37
- ##### Python Version 3.7.2
38
- ##### PyYaml Version 5.4.1 (Released Jan 20, 2021)
39
-
40
- ----
41
-
42
- ## What is Python?
43
- Python is an interpreted high-level general-purpose programming language. Python's design philosophy emphasizes code readability with its notable use of significant indentation. Its language constructs as well as its object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.
44
-
45
- [source](https://en.wikipedia.org/wiki/Python_(programming_language))
46
- ## What is PyYaml?
47
- YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python.
48
-
49
- PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object.
50
-
51
- PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistence.
52
-
53
- [source](https://pypi.org/project/PyYAML/)
54
- ## Libraries
55
- * Config: overlay of PyYaml library (read-only), use Tool and Logger library (rkt_tool_lib, rkt_logger_lib)
56
-
57
- ## Use it
58
- ### Install
59
- ```bash
60
- (venv) my_project> pip install rkt_config_lib [--index-url https://gitlab.tprc.ovh/api/v4/groups/python/-/packages/pypi]
61
- ```
62
- ### Example
63
- ```python
64
- from rkt_config_lib import Config
65
-
66
- c = Config()
67
-
68
- # by default search folder named "config" in root project folder
69
- # for load all yaml files
70
- c.get_data()
71
-
72
- print(f"{c.data}")
73
- ```
74
-
75
- ### Output (as file, sdtout or both)
76
- ```log
77
- 03/03/2022 16:44:09 :: [Logger] :: INFO :: Create logger for 'Config'
78
- 03/03/2022 16:44:09 :: [Logger] :: INFO :: add 'StreamHandler' in 'Config' logger
79
- 03/03/2022 16:44:09 :: [Logger] :: INFO :: add 'FileHandler' in 'Config' logger
80
- 03/03/2022 16:44:09 :: [Config] :: INFO :: Load 'database' file ...
81
- ```
82
- ```
83
- {'database': {'connect_id': {'dbms': 'mariadb'}}}
84
- ^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
85
- | |
86
- | data: file content
87
- file name without extension
88
- ```
89
-
90
- ## Contributing
91
-
92
- If you find this library useful here's how you can help:
93
-
94
- - Send a merge request with your kickass new features and bug fixes
95
- - Help new users with [issues](https://gitlab.tprc.ovh/python/rkt_lib_toolkit/-/issues) they may encounter
96
- - Support the development of this library and star this repo!
97
-
98
-
@@ -1,9 +0,0 @@
1
- LICENSE
2
- README
3
- rkt_lib_toolkit/config/Config.py
4
- rkt_lib_toolkit/config/__init__.py
5
- rkt_lib_toolkit/rkt_config_lib.egg-info/PKG-INFO
6
- rkt_lib_toolkit/rkt_config_lib.egg-info/SOURCES.txt
7
- rkt_lib_toolkit/rkt_config_lib.egg-info/dependency_links.txt
8
- rkt_lib_toolkit/rkt_config_lib.egg-info/requires.txt
9
- rkt_lib_toolkit/rkt_config_lib.egg-info/top_level.txt
File without changes