mooch.settings 0.0.1.dev1__py3-none-any.whl

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.
mooch/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """mooch package initialization."""
2
+
3
+ from pkgutil import extend_path
4
+
5
+ __path__ = extend_path(__path__, __name__)
@@ -0,0 +1,4 @@
1
+
2
+ from mooch.settings.settings import Settings
3
+
4
+ __all__ = ["Settings"]
mooch/settings/file.py ADDED
@@ -0,0 +1,41 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime, timezone
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ import toml
8
+
9
+ from mooch.settings.utils import set_nested
10
+
11
+ NOTICE_KEY = "metadata.notice"
12
+ NOTICE = "This file was created by mooch.settings."
13
+ CREATED_KEY = "metadata.created"
14
+ UPDATED_KEY = "metadata.updated"
15
+
16
+
17
+ class File:
18
+ def __init__(self, settings_filepath: Path) -> None:
19
+ self._filepath = settings_filepath
20
+ self.create_file_if_not_exists()
21
+
22
+ def create_file_if_not_exists(self) -> None:
23
+ """Create the settings file if it does not exist."""
24
+ if not self._filepath.exists():
25
+ data = {}
26
+ set_nested(data, NOTICE_KEY, NOTICE)
27
+ set_nested(data, CREATED_KEY, datetime.now(tz=timezone.utc).isoformat())
28
+ set_nested(data, UPDATED_KEY, datetime.now(tz=timezone.utc).isoformat())
29
+
30
+ self.save(data)
31
+
32
+ def load(self) -> dict[str, Any]:
33
+ """Load the settings from the file."""
34
+ with Path.open(self._filepath, mode="r", encoding="utf-8") as f:
35
+ return toml.load(f)
36
+
37
+ def save(self, data: dict) -> None:
38
+ """Save the settings to the file and update the updated timestamp."""
39
+ set_nested(data, UPDATED_KEY, datetime.now(tz=timezone.utc).isoformat())
40
+ with Path.open(self._filepath, mode="w", encoding="utf-8") as f:
41
+ toml.dump(data, f)
@@ -0,0 +1,76 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ from mooch.settings.file import File
7
+ from mooch.settings.utils import get_nested, set_nested
8
+
9
+
10
+ class Settings:
11
+ def __init__(
12
+ self,
13
+ settings_filepath: Path,
14
+ default_settings: dict | None = None,
15
+ ) -> None:
16
+ self._file = File(settings_filepath)
17
+ self.dynamic_reload = True
18
+
19
+ self._data = self._file.load()
20
+
21
+ if default_settings:
22
+ self._set_defaults(default_settings)
23
+ self._file.save(self._data)
24
+
25
+ @staticmethod
26
+ def home_directory() -> Path:
27
+ """Return the path to the home directory.
28
+
29
+ Returns: Path
30
+ """
31
+ return Path.home()
32
+
33
+ def get(self, key: str) -> Any | None: # noqa: ANN401
34
+ """Return a value from the configuration by key.
35
+
36
+ Args:
37
+ key (str): The key to return a value from.
38
+
39
+ Returns:
40
+ Any | None: The value associated with the key, or None if the key does not exist.
41
+
42
+ """
43
+ if self.dynamic_reload:
44
+ self._data = self._file.load()
45
+ return get_nested(self._data, key)
46
+
47
+ def set(self, key: str, value: Any) -> None: # noqa: ANN401
48
+ """Set a value in the configuration by key.
49
+
50
+ Args:
51
+ key (str): The key to store the value under.
52
+ value (Any): The value to set for the key.
53
+
54
+ Returns:
55
+ None
56
+
57
+ """
58
+ set_nested(self._data, key, value)
59
+ self._file.save(self._data)
60
+
61
+ def __getitem__(self, key: str) -> Any | None: # noqa: ANN401
62
+ """Get an item from the configuration by key."""
63
+ return self.get(key)
64
+
65
+ def __setitem__(self, key: str, value: Any) -> None: # noqa: ANN401
66
+ """Set an item in the configuration by key."""
67
+ self.set(key, value)
68
+
69
+ def _set_defaults(self, d: dict, parent_key: str = "") -> None:
70
+ for k, v in d.items():
71
+ full_key = f"{parent_key}.{k}" if parent_key else k
72
+ if self.get(full_key) is None:
73
+ self.set(full_key, v)
74
+
75
+ elif isinstance(v, dict):
76
+ self._set_defaults(v, full_key)
@@ -0,0 +1,24 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+
6
+ def set_nested(d: dict, key: str, value: Any, sep: str = ".") -> None: # noqa: ANN401
7
+ """Set a nested value in a dictionary by key."""
8
+ keys = key.split(sep)
9
+ for k in keys[:-1]:
10
+ if k not in d or not isinstance(d[k], dict):
11
+ d[k] = {}
12
+ d = d[k]
13
+ d[keys[-1]] = value
14
+
15
+
16
+ def get_nested(d: dict, key: str, sep: str = ".") -> Any | None: # noqa: ANN401
17
+ """Get a nested value from a dictionary by key."""
18
+ keys = key.split(sep)
19
+ for k in keys:
20
+ if isinstance(d, dict) and k in d:
21
+ d = d[k]
22
+ else:
23
+ return None
24
+ return d
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.4
2
+ Name: mooch.settings
3
+ Version: 0.0.1.dev1
4
+ Summary: Python settings management package (mooch.settings). Uses a TOML file.
5
+ Author-email: Nick Stuer <nickstuer@duck.com>
6
+ Project-URL: Homepage, https://github.com/nickstuer/mooch.settings
7
+ Project-URL: Issues, https://github.com/nickstuer/mooch.settings/issues
8
+ Classifier: Development Status :: 2 - Pre-Alpha
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: toml>=0.10.2
16
+ Dynamic: license-file
17
+
18
+ # Python mooch.settings
19
+
20
+ ![PyPI](https://img.shields.io/pypi/v/mooch.settings?label=mooch.settings)
21
+ ![PyPI - Downloads](https://img.shields.io/pypi/dm/mooch.settings)
22
+ <img alt="GitHub Issues or Pull Requests" src="https://img.shields.io/github/issues/nickstuer/mooch.settings">
23
+
24
+ [![standard-readme compliant](https://img.shields.io/badge/readme%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/RichardLitt/standard-readme)
25
+ [![license](https://img.shields.io/github/license/nickstuer/mooch.settings.svg)](LICENSE)
26
+
27
+ This Python package is a collection of useful Python code that is commonly used on all types of Python projects.
28
+
29
+ ## Table of Contents
30
+
31
+ - [Features](https://github.com/nickstuer/mooch.settings?tab=readme-ov-file#-features)
32
+ - [Install](https://github.com/nickstuer/mooch.settings?tab=readme-ov-file#-install)
33
+ - [Usage](https://github.com/nickstuer/mooch.settings?tab=readme-ov-file#-usage)
34
+ - [Contributing](https://github.com/nickstuer/mooch.settings?tab=readme-ov-file#-contributing)
35
+ - [License](https://github.com/nickstuer/mooch.settings?tab=readme-ov-file#-license)
36
+
37
+ ## 📖 Features
38
+
39
+
40
+ ### Settings File
41
+ Uses a TOML settings file. Easily get/set settingsuration values. Automatically sets values to defaults if they're not currently saved in the settingsuration file.
42
+
43
+
44
+ ## 🛠 Install
45
+
46
+ ```
47
+ # PyPI
48
+ pip install mooch.settings
49
+ ```
50
+ or
51
+ ```
52
+ uv add mooch.settings
53
+ ```
54
+
55
+ ## 📌 Dependencies
56
+ Python 3.9 or greater
57
+
58
+ ## 🎮 Usage
59
+
60
+ ### settings File
61
+ ```python
62
+ from mooch.settings import Settings
63
+ default_settings = {
64
+ "settings": {
65
+ "name": "MyName,
66
+ "mood": "happy",
67
+ },
68
+ }
69
+
70
+ settings = Settings("settings.toml", default_settings)
71
+
72
+ print(settings["settings.mood"])
73
+ settings["settings.mood"] = "angry"
74
+ print(settings["settings.mood"])
75
+ ```
76
+ ## 🏆 Contributing
77
+
78
+ PRs accepted.
79
+
80
+ If editing the Readme, please conform to the [standard-readme](https://github.com/RichardLitt/standard-readme) specification.
81
+
82
+ #### Bug Reports and Feature Requests
83
+ Please use the [issue tracker](https://github.com/nickstuer/mooch.settings/issues) to report any bugs or request new features.
84
+
85
+ #### Contributors
86
+
87
+ <a href = "https://github.com/nickstuer/mooch.settings/graphs/contributors">
88
+ <img src = "https://contrib.rocks/image?repo=nickstuer/mooch.settings"/>
89
+ </a>
90
+
91
+ ## 📃 License
92
+
93
+ [MIT © Nick Stuer](LICENSE)
@@ -0,0 +1,10 @@
1
+ mooch/__init__.py,sha256=_ZVUSDxucTCJe9q2wP1tI31qEX3m4QGcH7kn3BRv6ic,112
2
+ mooch/settings/__init__.py,sha256=Vs0DYdXwvsEU21Umpj893RoX2iSrL7n4Qb-5X4GYtiI,69
3
+ mooch/settings/file.py,sha256=aYwSe6PUhgZki9IF6mKsXVb3VkxEPVoQ2u8PzDoTAJY,1403
4
+ mooch/settings/settings.py,sha256=fL229LnQjte7UP5_cMFaM1YnqKh7LLV8sgWJkgW18jk,2152
5
+ mooch/settings/utils.py,sha256=V-aFKlrLaDfuJed4Yn-1pxlIM8jzdr4xRrNflBxLfXc,665
6
+ mooch_settings-0.0.1.dev1.dist-info/licenses/LICENSE,sha256=FU8uKPcPjgV4M_aaYQPSM5abrktGqLFX2VEUk9oBYIE,1067
7
+ mooch_settings-0.0.1.dev1.dist-info/METADATA,sha256=-K9SCr6DNS-IqsZvLlmUjp9fYRM6TwtR2pwmEGViwdU,2999
8
+ mooch_settings-0.0.1.dev1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
+ mooch_settings-0.0.1.dev1.dist-info/top_level.txt,sha256=BbCxYfdneRNeyhPyAVvt8IEDA_Px7BIm5zhH6hEmsAo,6
10
+ mooch_settings-0.0.1.dev1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Nick Stuer
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.
@@ -0,0 +1 @@
1
+ mooch