version-bumper 0.1.0__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.
@@ -0,0 +1,29 @@
1
+ # SPDX-FileCopyrightText: 2024 Roy Wright
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """
6
+ Documentation that will be shown with --longhelp goes here.
7
+ Consider using some of your README.md.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from importlib import metadata
13
+ from pathlib import Path
14
+
15
+ import tomlkit
16
+
17
+ try:
18
+ # this assumes running in an installed package
19
+ __version__ = metadata.version(__package__)
20
+ except metadata.PackageNotFoundError:
21
+ # this should only ever happen in the development environment,
22
+ # so ok to assume location of pyproject.toml file.
23
+ # Also assume src/package file layout and this file is in src/package
24
+ # and pyproject is in the parent directory of src
25
+ # ../../pyproject.toml
26
+ pyproject_path = Path(__file__).parent.parent.parent / "pyproject.toml"
27
+ with pyproject_path.open() as fp:
28
+ data = tomlkit.loads(fp.read()).value
29
+ __version__ = data["tool"]["poetry"]["version"] + "dev"
@@ -0,0 +1,214 @@
1
+ # SPDX-FileCopyrightText: 2024 Roy Wright
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """
6
+ This is a sample Python CLI script. Set up command line arguments in a class derived from ApplicationSettings.
7
+
8
+ You need to update the following class variables in Settings class to match your needs:
9
+
10
+ * project_name
11
+ * project_package
12
+ * project_description
13
+
14
+ and then add any arguments to Settings.add_arguments() and Settings.validate_arguments() methods.
15
+
16
+ Finally, add your application into the main() method.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import sys
22
+ from pathlib import Path
23
+ from typing import TYPE_CHECKING
24
+
25
+ from loguru import logger
26
+
27
+ from version_bumper.clibones.application_settings import ApplicationSettings
28
+ from version_bumper.commands import bump_command, get_command, release_command, set_command, version_command
29
+ from version_bumper.version import Version
30
+
31
+ if TYPE_CHECKING:
32
+ import argparse
33
+ from collections.abc import Sequence
34
+
35
+
36
+ # noinspection PyMethodMayBeStatic
37
+ class Settings(ApplicationSettings):
38
+ """Where the project's initial state (i.e. settings) are defined.
39
+
40
+ Settings extends the generic ApplicationSettings class which parses the command line arguments.
41
+
42
+ Usage::
43
+
44
+ with Settings() as settings:
45
+ try:
46
+ app.execute(settings)
47
+ exit(0)
48
+ except ArgumentError as ex:
49
+ error(str(ex))
50
+ exit(1)
51
+ """
52
+
53
+ __project_name: str = "Version Bumper"
54
+ """The name of the project"""
55
+
56
+ __project_package: str = "version_bumper"
57
+ """The name of the package this settings belongs to. """
58
+
59
+ __project_description: str = (
60
+ "Python package version utility to bump a version by parts: "
61
+ "[N!]N(.N)*[{a|b|rc}N][.postN][.devN][+N] "
62
+ "or with part names in lowercase: "
63
+ "[epoch!]major[.minor[.patch]][a|b|rc][.post][.dev][+local]"
64
+ )
65
+ """A short description of the application."""
66
+
67
+ def __init__(self, args: Sequence[str] | None = None) -> None:
68
+ """Initialize the base class."""
69
+
70
+ super().__init__(
71
+ app_name=Settings.__project_name,
72
+ app_package=Settings.__project_package,
73
+ app_description=Settings.__project_description,
74
+ config_sections=[Settings.__project_package],
75
+ args=args,
76
+ )
77
+ self.add_persist_keys({"pyproject_toml_path", "loglevel", "debug"})
78
+
79
+ def add_parent_parsers(self) -> list[argparse.ArgumentParser]:
80
+ """This is where you should add any parent parsers for the main parser.
81
+
82
+ :return: a list of parent parsers
83
+ """
84
+ return []
85
+
86
+ def add_arguments(self, parser: argparse.ArgumentParser, defaults: dict[str, str]) -> None: # noqa: ARG002
87
+ """This is where you should add arguments to the parser.
88
+
89
+ To add application arguments, you should override this method.
90
+
91
+ :param parser: the argument parser with --conf_file already added.
92
+ :param defaults: the default dictionary usually loaded from a config file
93
+ """
94
+ # use normal argparse commands to add arguments to the given parser. Example:
95
+
96
+ def add_common_arguments(_parser: argparse.ArgumentParser) -> None:
97
+ """
98
+ Add these arguments to the given parser.
99
+ """
100
+ _parser.add_argument(
101
+ "--pyproject",
102
+ dest="pyproject_toml_path",
103
+ default=pyproject_toml_path,
104
+ type=Path,
105
+ action="store",
106
+ help="pyproject.toml file update the version within.",
107
+ )
108
+
109
+ pyproject_toml_path = Path(__file__).parent.parent.parent.joinpath("pyproject.toml").resolve()
110
+
111
+ subparsers = parser.add_subparsers(dest="command")
112
+
113
+ bump_parser = subparsers.add_parser(
114
+ "bump", description="Bump the given part of the current version in the " "pyproject.toml file."
115
+ )
116
+ bump_parser.add_argument("part", choices=Version.PARTS, help="Bump this part of the current version")
117
+ bump_parser.add_argument(
118
+ "--json", action="store_true", help='Input is JSON string containing the part name to increment, ex: "dev"'
119
+ )
120
+ bump_parser.add_argument("--text", action="store_true", help='Input is text string, ex: "1.2.3rc1-dev3"')
121
+ add_common_arguments(bump_parser)
122
+
123
+ version_parser = subparsers.add_parser(
124
+ "version", description="Set the current version in the pyproject.toml file."
125
+ )
126
+ version_parser.add_argument("value", nargs="?", default="", type=str, help="Set the version to this value.")
127
+ version_parser.add_argument("--json", action="store_true", help='Input is JSON string, ex: "1.2.3rc1-dev3"')
128
+ version_parser.add_argument("--text", action="store_true", help='Input is text string, ex: "1.2.3rc1-dev3"')
129
+ version_parser.add_argument("--silent", action="store_true", help="Silence output (used for tests)")
130
+ add_common_arguments(version_parser)
131
+
132
+ set_parser = subparsers.add_parser(
133
+ "set", description="Set part of the current version in the pyproject.toml file " "to the given value."
134
+ )
135
+ set_parser.add_argument("part", choices=Version.PARTS, help="Set this part of the current version.")
136
+ set_parser.add_argument("value", nargs="?", default="", type=str, help="Set the version part to this value.")
137
+ set_parser.add_argument(
138
+ "--clear-right",
139
+ dest="clear_right",
140
+ action="store_true",
141
+ help="Clear the parts of the current version to the right of the part.",
142
+ )
143
+ set_parser.add_argument("--json", action="store_true", help='Input is JSON dictionary, ex: "{"rc": "1"}"')
144
+ set_parser.add_argument("--text", action="store_true", help='Input is text, ex: "rc1"')
145
+ add_common_arguments(set_parser)
146
+
147
+ get_parser = subparsers.add_parser("get", description="Get the current version from the pyproject.toml file.")
148
+ get_parser.add_argument("--project", action="store_true", help="Get the project.version value.")
149
+ get_parser.add_argument("--poetry", action="store_true", help="Get the tool.poetry.version value.")
150
+ get_parser.add_argument(
151
+ "--all", action="store_true", help="Get both project.version and tool.poetry.version values. [Default]"
152
+ )
153
+ get_parser.add_argument("--json", action="store_true", help='Output as JSON string, ex: "1.2.3rc1-dev"')
154
+ get_parser.add_argument("--text", action="store_true", help='Output as text string, ex: "1.2.3rc1-dev"')
155
+ add_common_arguments(get_parser)
156
+
157
+ release_parser = subparsers.add_parser(
158
+ "release", description="Change version to a release version, i.e. [N!]N[.N[.N]]"
159
+ )
160
+ release_parser.add_argument("--json", action="store_true", help='Output as JSON string, ex: "1.2.3"')
161
+ release_parser.add_argument("--text", action="store_true", help='Output as text string, ex: "1.2.3"')
162
+ add_common_arguments(release_parser)
163
+
164
+ def validate_arguments(self, settings: argparse.Namespace, remaining_argv: list[str]) -> list[str]: # noqa: ARG002
165
+ """This provides a hook for validating the settings after the parsing is completed.
166
+
167
+ :param settings: the settings object returned by ArgumentParser.parse_args()
168
+ :param remaining_argv: the remaining argv after the parsing is completed.
169
+ :return: a list of error messages or an empty list
170
+ """
171
+ errors: list[str] = []
172
+
173
+ # a command argument is required.
174
+ if settings.command is None:
175
+ errors.append(
176
+ "A command argument (set, get, bump, release, version) or an informational option "
177
+ "(--help, --longhelp, --version) is required"
178
+ )
179
+
180
+ # we want the default for the get command to get both project.version and tool.poetry.version.
181
+ # if a single argument is given (i.e., --project or --poetry), then we want to just get that version.
182
+ if settings.command == "get" and (not settings.project and not settings.poetry):
183
+ settings.project = True
184
+ settings.poetry = True
185
+
186
+ return errors
187
+
188
+
189
+ def main(args: list[str] | None = None) -> int:
190
+ """The command line applications main function."""
191
+ with Settings(args=args) as settings:
192
+ # some info commands (--version, --longhelp) need to exit immediately
193
+ # after completion. The quick_exit flag indicates if this is the case.
194
+ if settings.quick_exit:
195
+ return 0
196
+
197
+ commands = {
198
+ "set": set_command,
199
+ "get": get_command,
200
+ "bump": bump_command,
201
+ "release": release_command,
202
+ "version": version_command,
203
+ }
204
+
205
+ try:
206
+ commands[settings.command](settings)
207
+ except ValueError as ex:
208
+ logger.error(ex)
209
+ return 1
210
+ return 0
211
+
212
+
213
+ if __name__ == "__main__": # pragma: no cover
214
+ sys.exit(main(args=None))
@@ -0,0 +1,44 @@
1
+ # SPDX-FileCopyrightText: 2024 Roy Wright
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """
6
+ # CLI Bones
7
+
8
+ This application used [cookiecutter-clibones](https://github.com/royw/cookiecutter-clibones), a CLI application
9
+ framework based on the argparse standard library with loguru logging.
10
+ [Poetry](https://python-poetry.org/) and [Task](https://taskfile.dev/) are used for project
11
+ management.
12
+
13
+ ## Architecture
14
+
15
+ The architecture used is a Settings context manager that handles all the command line and config file argument
16
+ definition, parsing, and validation.
17
+
18
+ The application's entry point is in `version_bumper/__main__.py`
19
+ In `__main.py__` there several TODOs that you will need to visit and clear.
20
+
21
+ The application may be run with any of the following:
22
+
23
+ * `python3 -m clibones --help`
24
+ * `poetry run python3 -m clibones --help`
25
+ * `task main --help`
26
+
27
+ So in general, for each command line argument you ought to:
28
+
29
+ * optionally add an argument group to the parser in `Settings.add_arguments()`
30
+ * add argument to the parser in `Settings.add_arguments()`
31
+ * optionally add validation to `Settings.validate_arguments()`
32
+
33
+ Refer to `application_settings.py` which implements help and logging as examples.
34
+
35
+ The `__example_application()` demonstrates using a `GracefulInterruptHandler` to capture ^C for a main loop.
36
+
37
+ Next take a look at `main.main()` which demonstrates the use of the Settings context manager.
38
+
39
+ The `Settings` does have a few extra features including:
40
+
41
+ * config files are supported for any command arguments you want to persist.
42
+ * standard logging setup via command line arguments.
43
+
44
+ """
@@ -0,0 +1,210 @@
1
+ # SPDX-FileCopyrightText: 2024 Roy Wright
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """
6
+ A context manager base class that optionally reads a config file then uses the values as defaults
7
+ for command line argument parsing.
8
+
9
+ To be useful, you must derive a class from this base class, and you should override at least the **add_arguments**
10
+ method. You may find it useful to also override **_default_config_files** and **arguments_validate** methods.
11
+
12
+ This base class adds the following features to ArgumentParser:
13
+
14
+ * config file support from either the command line (--config FILE) or from expected locations (current
15
+ directory then user's home directory). The default config file name is created by prepending '.' and appending
16
+ 'rc' to the applications package name (example, app_package = 'foobar', then config file name would be
17
+ '.local/foobar.conf' or '.foobarrc' and the search order would be: ['./.foobarrc', '~/.local/foobar.conf']).
18
+
19
+ * display the application's --version from app_package.version (usually defined in app_package/__init__.py).
20
+
21
+ * display the application's --longhelp which is the module docstring in app_package/__init__.py.
22
+
23
+ * initializing the root logging using --verbosity LEVEL, --quiet, --debug, and --logfile FILENAME
24
+
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import sys
31
+ from abc import ABC, abstractmethod
32
+ from pathlib import Path
33
+ from typing import TYPE_CHECKING, Any
34
+
35
+ from version_bumper.clibones.config_file import ConfigFile
36
+ from version_bumper.clibones.info_control import InfoControl
37
+ from version_bumper.clibones.logger_control import LoggerControl
38
+
39
+ if TYPE_CHECKING:
40
+ from collections.abc import Sequence
41
+
42
+
43
+ class ApplicationSettings(ABC):
44
+ """
45
+ Usage::
46
+
47
+ class MySettings(ApplicationSettings):
48
+ def __init__(self):
49
+ super(MySettings, self).__init__("App Name", "app_package", "app_description", ["APP Section"])
50
+
51
+ def add_arguments(parser):
52
+ parser.add_argument("--foo", action="store_true", help="It's all about foo")
53
+ parser.add_argument("--bar", action="store_true", help="Just the best, bar none")
54
+
55
+ Context Manager Usage::
56
+
57
+ with MySettings() as settings:
58
+ if settings.foo:
59
+ pass
60
+
61
+ Traditional Usage::
62
+
63
+ parser, settings = MySettings().parse()
64
+ if settings.foo:
65
+ pass
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ app_name: str,
71
+ app_package: str,
72
+ app_description: str,
73
+ config_sections: list[str],
74
+ default_config_file: Path | None = None,
75
+ args: Sequence[str] | None = None,
76
+ ) -> None:
77
+ """
78
+ :param str app_name: The application name
79
+ :param app_package: The application's package name
80
+ :param default_config_file: The default config file to load, None means no default config file.
81
+ :param args: A list of arguments to pass to the application. If none then get arguments from sys.argv
82
+ """
83
+ self.__app_name: str = app_name
84
+ self.__app_package: str = app_package
85
+ self.__app_description = app_description
86
+ self.__config_sections: list[str] = config_sections
87
+ self.__default_config_file: Path | None = default_config_file
88
+ self.__args: Sequence[str] = args or sys.argv[1:]
89
+
90
+ self._parser: argparse.ArgumentParser | None = None
91
+ self._settings: argparse.Namespace | None = None
92
+ self._remaining_argv: list[str] = []
93
+ self._persist_keys: set[str] = set()
94
+ self.quick_exit: bool = False
95
+ self.logger_control = LoggerControl()
96
+ self.info_control = InfoControl(app_package=app_package)
97
+
98
+ if self.__default_config_file is None:
99
+ self.__default_config_file = Path.home() / ".config" / f"{self.__app_package}.toml"
100
+
101
+ @abstractmethod
102
+ def add_parent_parsers(self) -> list[argparse.ArgumentParser]: # pragma: no cover
103
+ """
104
+ This is where you should add any parent parsers for the main parser.
105
+
106
+ :return: a list of parent parsers
107
+ """
108
+ return []
109
+
110
+ @abstractmethod
111
+ def add_arguments(self, parser: argparse.ArgumentParser, defaults: dict[str, str]) -> None: # pragma: no cover
112
+ """
113
+ This is where you should add arguments to the parser.
114
+
115
+ To add application arguments, you should override this method.
116
+
117
+ :param parser: the argument parser with --config already added.
118
+ :param defaults: the default dictionary usually loaded from a config file
119
+ """
120
+ return
121
+
122
+ @abstractmethod
123
+ def validate_arguments(
124
+ self, settings: argparse.Namespace, remaining_argv: list[str]
125
+ ) -> list[str]: # pragma: no cover
126
+ """
127
+ This provides a hook for validating the settings after the parsing is completed.
128
+
129
+ :param settings: the settings object returned by ArgumentParser.parse_args()
130
+ :param remaining_argv: the remaining argv after the parsing is completed.
131
+ :return: a list of error messages or an empty list
132
+ """
133
+ return []
134
+
135
+ def add_persist_keys(self, keys: set[str]) -> None:
136
+ self._persist_keys |= keys
137
+
138
+ def parse(self, args: Sequence[str]) -> tuple[argparse.ArgumentParser, argparse.Namespace, list[str]]:
139
+ """
140
+ Perform the parsing of the optional config files and the command line arguments.
141
+
142
+ return: the parser, the settings, and any remaining arguments.
143
+ """
144
+ config_file = ConfigFile()
145
+ config_file.default_config_file = self.__default_config_file
146
+ config_file.section_name = self.__app_package
147
+ config_file.persist_keys = self._persist_keys
148
+ dash_config_parser, remaining_args, defaults = config_file.parser(args=args)
149
+
150
+ parser = argparse.ArgumentParser(
151
+ self.__app_name,
152
+ parents=[dash_config_parser, *self.add_parent_parsers()],
153
+ description=self.__app_description,
154
+ )
155
+
156
+ # add arguments to the parser
157
+ self.info_control.add_arguments(parser=parser)
158
+ self.logger_control.add_arguments(parser=parser)
159
+ self.add_arguments(parser=parser, defaults=defaults or {})
160
+
161
+ if defaults:
162
+ parser.set_defaults(**defaults)
163
+
164
+ # drum roll... Perform the parse!
165
+ settings, leftover_args = parser.parse_known_args(args=remaining_args)
166
+
167
+ # copy quick_exit into namespace for context usage
168
+ settings.quick_exit = self.quick_exit
169
+ settings.config_file = config_file.config_filepath
170
+
171
+ config_file.save_config_file(vars(settings))
172
+
173
+ return parser, settings, leftover_args
174
+
175
+ def __enter__(self) -> argparse.Namespace:
176
+ """context manager enter
177
+ :return: the settings namespace
178
+ """
179
+ self._parser, self._settings, self._remaining_argv = self.parse(args=self.__args)
180
+
181
+ self.logger_control.setup(self._settings)
182
+ self.info_control.setup(self._settings)
183
+
184
+ if not self._settings.quick_exit:
185
+ # validate both the base ApplicationSettings.validate_arguments and the child's validate_arguments.
186
+ # combine the results which each can be either a list of error message strings or an empty list
187
+ error_messages: list[str] = ApplicationSettings.validate_arguments(
188
+ self, self._settings, self._remaining_argv
189
+ ) + self.validate_arguments(self._settings, self._remaining_argv)
190
+
191
+ for error_msg in error_messages:
192
+ self._parser.error(error_msg)
193
+
194
+ self._settings.parser = self._parser
195
+ return self._settings
196
+
197
+ def __exit__(self, *exc: Any) -> None: # NOQA: B027
198
+ """
199
+ context manager exit
200
+ """
201
+
202
+ def help(self) -> int:
203
+ """
204
+ Let the parser print the help message.
205
+
206
+ :return: 2
207
+ """
208
+ if self._parser:
209
+ self._parser.print_help()
210
+ return 2
@@ -0,0 +1,157 @@
1
+ # SPDX-FileCopyrightText: 2024 Roy Wright
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ from __future__ import annotations
6
+
7
+ import argparse
8
+ from collections.abc import Callable
9
+ from dataclasses import dataclass
10
+ from json import JSONDecodeError
11
+ from pathlib import Path
12
+ from typing import TYPE_CHECKING, Any
13
+
14
+ import tomlkit.parser
15
+
16
+ from version_bumper.clibones.config_file_base import ConfigFileBase
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import Sequence
20
+
21
+ # ================================================================================
22
+ # Add import of format specific config file then add to SUPPORTED_FORMATS list
23
+ from version_bumper.clibones.json_config_file import JsonConfigFile
24
+ from version_bumper.clibones.toml_config_file import TomlConfigFile
25
+
26
+ SUPPORTED_FORMATS: list[type[ConfigFileBase]] = [TomlConfigFile, JsonConfigFile]
27
+ # ================================================================================
28
+
29
+
30
+ @dataclass
31
+ class ConfigFile:
32
+ """
33
+ Reading and writing config files of multiple file formats.
34
+ Converts any exceptions in load or save to ValueError.
35
+
36
+ Usage:
37
+
38
+ config_file = ConfigFile()
39
+ config_data = config_file.load(f"{app_name}.toml")
40
+ with Settings() as settings:
41
+ config_file.save(f"{app_name}.toml", settings)
42
+ """
43
+
44
+ persist_keys: set[str] | None = None
45
+ section_name: str | None = None
46
+ default_config_file: Path | None = None
47
+ config_filepath: Path | None = None
48
+ save_config_filepath: Path | None = None
49
+
50
+ def __init__(self) -> None:
51
+ self.registered_formats: dict[
52
+ str, tuple[Callable[[Path], dict[str, Any]], Callable[[Path, dict[str, Any]], None]]
53
+ ] = {}
54
+ self.supported_formats: list[type[ConfigFileBase]] = SUPPORTED_FORMATS
55
+ for supported_format in self.supported_formats:
56
+ supported_format.register(self)
57
+
58
+ def register(
59
+ self, extension: str, loader: Callable[[Path], dict[str, Any]], saver: Callable[[Path, dict[str, Any]], None]
60
+ ) -> None:
61
+ """register an extension with loader and saver methods."""
62
+ self.registered_formats[extension] = (loader, saver)
63
+
64
+ @property
65
+ def supported_extensions(self) -> list[str]:
66
+ """return the list of supported extensions. Note the extension includes the leading dot (ex: ".toml")"""
67
+ return list(self.registered_formats.keys())
68
+
69
+ def load(self, filepath: Path | None) -> dict[str, Any]:
70
+ """
71
+ load config file return a dictionary with the loaded data.
72
+
73
+ raises: ValueError
74
+ """
75
+ if filepath is None:
76
+ return {}
77
+
78
+ try:
79
+ return self.registered_formats[filepath.suffix][0](filepath)
80
+ except ValueError as ex:
81
+ raise ex
82
+ except KeyError as ex:
83
+ errmsg = f"No config file loader found for {filepath}"
84
+ raise ValueError(errmsg) from ex
85
+ except (JSONDecodeError, tomlkit.parser.ParseError, TypeError) as ex:
86
+ errmsg = f"The config file ({filepath}) could not be loaded: {ex}"
87
+ raise ValueError(errmsg) from ex
88
+
89
+ def save(self, filepath: Path, config_dict: dict[str, Any]) -> None:
90
+ """
91
+ save config file given a dictionary with the data to save.
92
+
93
+ raises: ValueError
94
+ """
95
+ if not isinstance(config_dict, dict):
96
+ errmsg = f"The config file ({filepath}) must be a dictionary" # type: ignore[unreachable]
97
+ raise ValueError(errmsg)
98
+ try:
99
+ self.registered_formats[filepath.suffix][1](filepath, config_dict)
100
+ except ValueError as ex:
101
+ raise ex
102
+ except KeyError as ex:
103
+ errmsg = f"No config file saver found for {filepath}"
104
+ raise ValueError(errmsg) from ex
105
+ except (JSONDecodeError, tomlkit.parser.ParseError, TypeError) as ex:
106
+ errmsg = f"Cannot convert the data to the format of the config file {filepath}: {ex}"
107
+ raise ValueError(errmsg) from ex
108
+
109
+ def parser(self, args: Sequence[str]) -> tuple[argparse.ArgumentParser, Sequence[str], dict[str, Any] | None]:
110
+ config_parser_help = f"Configuration file (default: {self.default_config_file})"
111
+ dash_config_parser: argparse.ArgumentParser = argparse.ArgumentParser(add_help=False)
112
+ dash_config_parser.add_argument("--config", metavar="FILE", help=config_parser_help)
113
+ dash_config_parser.add_argument(
114
+ "--save-config", dest="save_config", action="store_true", help=config_parser_help
115
+ )
116
+ dash_config_parser.add_argument("--save-config-as", metavar="FILE", help=config_parser_help)
117
+ parse_args, remaining_args = dash_config_parser.parse_known_args(args=args)
118
+
119
+ # desired config files may also be located in self.__config_files and in self._default_config_files(),
120
+ # so combine the three possible sources with the "--config FILE" being first in the list.
121
+ self.config_filepath = self.default_config_file
122
+ if parse_args.config:
123
+ self.config_filepath = Path(parse_args.config)
124
+ if parse_args.save_config:
125
+ self.save_config_filepath = self.config_filepath
126
+ if parse_args.save_config_as:
127
+ self.save_config_filepath = Path(parse_args.save_config_as)
128
+
129
+ defaults: dict[str, Any] = {}
130
+ if self.config_filepath is not None:
131
+ try:
132
+ data = self.load(self.config_filepath)
133
+ if self.section_name in data:
134
+ defaults = self.filter_keys(data[self.section_name], self.persist_keys or set(), defaults)
135
+ except FileNotFoundError:
136
+ # the config file doesn't exist, which is ok and means no defaults...
137
+ pass
138
+ return dash_config_parser, remaining_args, defaults
139
+
140
+ @staticmethod
141
+ def filter_keys(data: dict[str, Any], persist_keys: set[str], filtered_data: dict[str, Any]) -> dict[str, Any]:
142
+ for key in data:
143
+ if key in persist_keys:
144
+ filtered_data[key] = data[key]
145
+ return filtered_data
146
+
147
+ def save_config_file(self, settings: dict[str, Any]) -> None:
148
+ data = {}
149
+ if self.save_config_filepath:
150
+ if self.persist_keys:
151
+ for key in self.persist_keys:
152
+ if key in settings:
153
+ data[key] = settings[key]
154
+
155
+ self.save(
156
+ filepath=self.save_config_filepath, config_dict={self.section_name or "missing section_name": data}
157
+ )
@@ -0,0 +1,26 @@
1
+ # SPDX-FileCopyrightText: 2024 Roy Wright
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ from __future__ import annotations
6
+
7
+ from abc import ABC, abstractmethod
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+
12
+ class ConfigFileBase(ABC):
13
+ @staticmethod
14
+ @abstractmethod
15
+ def register(config_file: Any) -> None:
16
+ pass
17
+
18
+ @staticmethod
19
+ @abstractmethod
20
+ def load(filepath: Path) -> dict[str, Any]:
21
+ pass
22
+
23
+ @staticmethod
24
+ @abstractmethod
25
+ def save(filepath: Path, config_dict: dict[str, Any]) -> None:
26
+ pass