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.
- version_bumper/__init__.py +29 -0
- version_bumper/__main__.py +214 -0
- version_bumper/clibones/__init__.py +44 -0
- version_bumper/clibones/application_settings.py +210 -0
- version_bumper/clibones/config_file.py +157 -0
- version_bumper/clibones/config_file_base.py +26 -0
- version_bumper/clibones/info_control.py +83 -0
- version_bumper/clibones/json_config_file.py +35 -0
- version_bumper/clibones/logger_control.py +114 -0
- version_bumper/clibones/toml_config_file.py +34 -0
- version_bumper/commands.py +157 -0
- version_bumper/pyproject.py +50 -0
- version_bumper/version.py +456 -0
- version_bumper-0.1.0.dist-info/METADATA +284 -0
- version_bumper-0.1.0.dist-info/RECORD +17 -0
- version_bumper-0.1.0.dist-info/WHEEL +4 -0
- version_bumper-0.1.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2024 Roy Wright
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import importlib
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from importlib import metadata
|
|
10
|
+
from typing import TYPE_CHECKING
|
|
11
|
+
|
|
12
|
+
from loguru import logger
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
import argparse
|
|
16
|
+
from argparse import ArgumentParser
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class InfoControl:
|
|
21
|
+
"""Add information control (--version, --longhelp) argument support to a CLI application."""
|
|
22
|
+
|
|
23
|
+
DEFAULT_VERSION: str = "Unknown"
|
|
24
|
+
|
|
25
|
+
app_package: str | None = None
|
|
26
|
+
|
|
27
|
+
# noinspection PyMethodMayBeStatic
|
|
28
|
+
def add_arguments(self, parser: ArgumentParser) -> ArgumentParser:
|
|
29
|
+
"""Use argparse commands to add arguments to the given parser."""
|
|
30
|
+
info_group = parser.add_argument_group(title="Informational Commands", description="")
|
|
31
|
+
|
|
32
|
+
info_group.add_argument(
|
|
33
|
+
"-v",
|
|
34
|
+
"--version",
|
|
35
|
+
dest="version",
|
|
36
|
+
action="store_true",
|
|
37
|
+
help="Show the application's version. (default: %(default)s)",
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
info_group.add_argument(
|
|
41
|
+
"--longhelp",
|
|
42
|
+
dest="longhelp",
|
|
43
|
+
action="store_true",
|
|
44
|
+
help="Verbose help message. (default: %(default)s)",
|
|
45
|
+
)
|
|
46
|
+
return parser
|
|
47
|
+
|
|
48
|
+
def setup(self, settings: argparse.Namespace) -> None:
|
|
49
|
+
"""Set up the given settings. In this case, handle the --version and --longhelp options."""
|
|
50
|
+
if settings.longhelp and self.app_package:
|
|
51
|
+
logger.info(self._load_longhelp())
|
|
52
|
+
settings.quick_exit = True
|
|
53
|
+
|
|
54
|
+
if settings.version and not settings.quick_exit:
|
|
55
|
+
logger.info(f"Version {self._load_version()}")
|
|
56
|
+
settings.quick_exit = True
|
|
57
|
+
|
|
58
|
+
def _load_version(self) -> str:
|
|
59
|
+
r"""
|
|
60
|
+
Get the version from the application package's __version__ attribute.
|
|
61
|
+
If not found then return DEFAULT_VERSION
|
|
62
|
+
|
|
63
|
+
:return: the version string or DEFAULT_VERSION
|
|
64
|
+
"""
|
|
65
|
+
if self.app_package:
|
|
66
|
+
try:
|
|
67
|
+
return metadata.version(self.app_package)
|
|
68
|
+
except (ImportError, importlib.metadata.PackageNotFoundError):
|
|
69
|
+
logger.warning(f"Could not get metadata for {self.app_package}")
|
|
70
|
+
try:
|
|
71
|
+
return str(__import__(self.app_package).version)
|
|
72
|
+
except (ImportError, AttributeError, ValueError):
|
|
73
|
+
logger.warning(f"Could not import {self.app_package}.version")
|
|
74
|
+
return InfoControl.DEFAULT_VERSION
|
|
75
|
+
|
|
76
|
+
def _load_longhelp(self) -> str:
|
|
77
|
+
errmsg: str = f"Long Help not available. Please add docstring to {self.app_package}.__init__.py"
|
|
78
|
+
try:
|
|
79
|
+
app_module = importlib.import_module(str(self.app_package))
|
|
80
|
+
except (ModuleNotFoundError, TypeError):
|
|
81
|
+
return errmsg
|
|
82
|
+
else:
|
|
83
|
+
return app_module.__doc__ or errmsg
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2024 Roy Wright
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import tempfile
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from version_bumper.clibones.config_file_base import ConfigFileBase
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class JsonConfigFile(ConfigFileBase):
|
|
16
|
+
@staticmethod
|
|
17
|
+
def register(config_file: Any) -> None:
|
|
18
|
+
config_file.register(".json", JsonConfigFile.load, JsonConfigFile.save)
|
|
19
|
+
|
|
20
|
+
@staticmethod
|
|
21
|
+
def load(filepath: Path) -> dict[str, Any]:
|
|
22
|
+
with filepath.open(encoding="utf-8") as f:
|
|
23
|
+
data = json.load(f)
|
|
24
|
+
if isinstance(data, dict):
|
|
25
|
+
return data
|
|
26
|
+
errmsg = f'Data loaded from "{filepath}" is not a dictionary.'
|
|
27
|
+
raise ValueError(errmsg)
|
|
28
|
+
|
|
29
|
+
@staticmethod
|
|
30
|
+
def save(filepath: Path, config_dict: dict[str, Any]) -> None:
|
|
31
|
+
# write to temporary file then atomically "switch" it with the original using rename.
|
|
32
|
+
with tempfile.NamedTemporaryFile("wt", dir=filepath.parent, delete=False) as tf:
|
|
33
|
+
tf.write(json.dumps(config_dict))
|
|
34
|
+
temp_name = Path(tf.name)
|
|
35
|
+
temp_name.rename(filepath)
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2024 Roy Wright
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import sys
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
|
|
12
|
+
from loguru import logger
|
|
13
|
+
from pathvalidate.argparse import validate_filepath_arg
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from argparse import ArgumentParser
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
# Default loguru format for colorized output
|
|
20
|
+
LOGURU_FORMAT = (
|
|
21
|
+
"<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
|
|
22
|
+
"<level>{level: <8}</level> | "
|
|
23
|
+
"<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
|
|
24
|
+
)
|
|
25
|
+
# removed the timestamp from the logs
|
|
26
|
+
LOGURU_MEDIUM_FORMAT = "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
|
|
27
|
+
# just the colorized message in the logs
|
|
28
|
+
LOGURU_SHORT_FORMAT = "<level>{message}</level>"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class LoggerControl:
|
|
32
|
+
"""Add logger control arguments (--loglevel, --debug, --quiet, --logfile) to CLI application."""
|
|
33
|
+
|
|
34
|
+
VALID_LOG_LEVELS: Sequence[str] = (
|
|
35
|
+
"DEBUG",
|
|
36
|
+
"INFO",
|
|
37
|
+
"WARNING",
|
|
38
|
+
"ERROR",
|
|
39
|
+
"CRITICAL",
|
|
40
|
+
) # cannot select NOTSET
|
|
41
|
+
|
|
42
|
+
# noinspection PyMethodMayBeStatic
|
|
43
|
+
def add_arguments(self, parser: ArgumentParser) -> None:
|
|
44
|
+
"""Use argparse commands to add arguments to the given parser."""
|
|
45
|
+
|
|
46
|
+
output_group = parser.add_argument_group(title="Logging Options", description="output_group")
|
|
47
|
+
|
|
48
|
+
output_group.add_argument(
|
|
49
|
+
"--loglevel",
|
|
50
|
+
dest="loglevel",
|
|
51
|
+
default="INFO",
|
|
52
|
+
choices=LoggerControl.VALID_LOG_LEVELS,
|
|
53
|
+
help=f'Set verbosity level to one of the following: {LoggerControl.VALID_LOG_LEVELS} (default: "INFO").',
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
output_group.add_argument(
|
|
57
|
+
"--debug",
|
|
58
|
+
dest="debug",
|
|
59
|
+
action="store_true",
|
|
60
|
+
help="Output all messages (debug, info, warning, error, & critical). " 'Overrides "--loglevel".',
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
output_group.add_argument(
|
|
64
|
+
"--quiet",
|
|
65
|
+
dest="quiet",
|
|
66
|
+
action="store_true",
|
|
67
|
+
help='Only output error and critical messages. Overrides "--loglevel" ' 'and "--debug".',
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
output_group.add_argument(
|
|
71
|
+
"--logfile",
|
|
72
|
+
dest="logfile",
|
|
73
|
+
action="store",
|
|
74
|
+
type=validate_filepath_arg,
|
|
75
|
+
help='File to log messages enabled by "--loglevel" to.',
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
@staticmethod
|
|
79
|
+
def setup(settings: argparse.Namespace) -> None:
|
|
80
|
+
level = "INFO"
|
|
81
|
+
error_messages = []
|
|
82
|
+
|
|
83
|
+
# convert settings to dictionary, so we can test if argument was passed
|
|
84
|
+
settings_dict: dict[str, Any] = vars(settings)
|
|
85
|
+
|
|
86
|
+
# the order of the loglevel processing is important.
|
|
87
|
+
# --quiet has the highest priority followed by --debug then --loglevel
|
|
88
|
+
if "loglevel" in settings_dict:
|
|
89
|
+
level = settings_dict["loglevel"]
|
|
90
|
+
if level not in LoggerControl.VALID_LOG_LEVELS:
|
|
91
|
+
error_messages.append(
|
|
92
|
+
f"Invalid log level {level}, " f"should be one of the following: {LoggerControl.VALID_LOG_LEVELS}"
|
|
93
|
+
)
|
|
94
|
+
level = "INFO"
|
|
95
|
+
|
|
96
|
+
if settings_dict.get("debug"):
|
|
97
|
+
level = "DEBUG"
|
|
98
|
+
|
|
99
|
+
if settings_dict.get("quiet"):
|
|
100
|
+
level = "ERROR"
|
|
101
|
+
|
|
102
|
+
settings.loglevel = level
|
|
103
|
+
logger.remove(None)
|
|
104
|
+
logger.add(sys.stdout, level=settings.loglevel, format=LOGURU_SHORT_FORMAT)
|
|
105
|
+
|
|
106
|
+
if settings_dict.get("logfile"):
|
|
107
|
+
filename = settings_dict["logfile"]
|
|
108
|
+
try:
|
|
109
|
+
logger.add(filename, level=settings.loglevel)
|
|
110
|
+
except OSError as ex:
|
|
111
|
+
error_messages += [f"Could not open logfile ({filename}): {ex}"]
|
|
112
|
+
|
|
113
|
+
for msg in error_messages:
|
|
114
|
+
logger.error(msg)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2024 Roy Wright
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import tempfile
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import tomlkit
|
|
12
|
+
|
|
13
|
+
from version_bumper.clibones.config_file_base import ConfigFileBase
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TomlConfigFile(ConfigFileBase):
|
|
17
|
+
@staticmethod
|
|
18
|
+
def register(config_file: Any) -> None:
|
|
19
|
+
config_file.register(".toml", TomlConfigFile.load, TomlConfigFile.save)
|
|
20
|
+
config_file.register(".tml", TomlConfigFile.load, TomlConfigFile.save)
|
|
21
|
+
|
|
22
|
+
@staticmethod
|
|
23
|
+
def load(filepath: Path) -> dict[str, Any]:
|
|
24
|
+
with filepath.open(encoding="utf-8") as f:
|
|
25
|
+
data: dict[str, Any] = tomlkit.load(f).value
|
|
26
|
+
return data
|
|
27
|
+
|
|
28
|
+
@staticmethod
|
|
29
|
+
def save(filepath: Path, config_dict: dict[str, Any]) -> None:
|
|
30
|
+
# write to temporary file then atomically "switch" it with the original using rename.
|
|
31
|
+
with tempfile.NamedTemporaryFile("wt", dir=filepath.parent, delete=False) as tf:
|
|
32
|
+
tf.write(tomlkit.dumps(config_dict))
|
|
33
|
+
temp_name = Path(tf.name)
|
|
34
|
+
temp_name.rename(filepath)
|
|
@@ -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
|
+
import json
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from loguru import logger
|
|
12
|
+
|
|
13
|
+
from version_bumper.pyproject import PyProject
|
|
14
|
+
from version_bumper.version import Version
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def version_command(settings: argparse.Namespace) -> None:
|
|
18
|
+
"""
|
|
19
|
+
Set the version in the pyproject.toml file.
|
|
20
|
+
"""
|
|
21
|
+
__save_version(pyproject_toml_path=settings.pyproject_toml_path, version=Version(settings.value))
|
|
22
|
+
if not settings.silent:
|
|
23
|
+
__output(settings=settings, versions={"version": str(settings.value)})
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def get_command(settings: argparse.Namespace) -> None:
|
|
27
|
+
"""
|
|
28
|
+
Get the version (project.version, or tool.poetry.version, or both) from the pyproject.toml file.
|
|
29
|
+
"""
|
|
30
|
+
versions: dict[str, str] = {}
|
|
31
|
+
keys: list[str] = []
|
|
32
|
+
|
|
33
|
+
keys.append("project.version") if settings.project else None
|
|
34
|
+
keys.append("tool.poetry.version") if settings.poetry else None
|
|
35
|
+
|
|
36
|
+
version_list: list[Version | None] = PyProject.load_version(
|
|
37
|
+
pyproject_toml_path=settings.pyproject_toml_path, key_dot_notation_list=keys
|
|
38
|
+
)
|
|
39
|
+
if settings.project and version_list is not None:
|
|
40
|
+
versions["project.version"] = str(version_list.pop(0))
|
|
41
|
+
|
|
42
|
+
if settings.poetry and version_list is not None:
|
|
43
|
+
versions["tool.poetry.version"] = str(version_list.pop(0))
|
|
44
|
+
__output(settings=settings, versions=versions)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def bump_command(settings: argparse.Namespace) -> None:
|
|
48
|
+
"""
|
|
49
|
+
A version consists of several parts: epoch, major, minor, patch, release, a, b, rc, post, dev, and local.
|
|
50
|
+
This method allows incrementing any of the individual parts.
|
|
51
|
+
"""
|
|
52
|
+
version: Version | None = __load_version(settings=settings)
|
|
53
|
+
if version is None:
|
|
54
|
+
errmsg = (
|
|
55
|
+
f"Unable to extract neither project.version nor tool.poetry.version "
|
|
56
|
+
f" from {settings.pyproject_toml_path}"
|
|
57
|
+
)
|
|
58
|
+
raise ValueError(errmsg)
|
|
59
|
+
|
|
60
|
+
version.bump(part=settings.part)
|
|
61
|
+
__save_version(pyproject_toml_path=settings.pyproject_toml_path, version=version)
|
|
62
|
+
__output(settings=settings, versions={"version": str(version)})
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def release_command(settings: argparse.Namespace) -> None:
|
|
66
|
+
"""
|
|
67
|
+
A release version consists of several parts: epoch, major, minor, and patch.
|
|
68
|
+
This method removes the remaining parts: a, b, rc, post, dev, and local.
|
|
69
|
+
"""
|
|
70
|
+
version: Version | None = __load_version(settings)
|
|
71
|
+
if version is None:
|
|
72
|
+
errmsg = (
|
|
73
|
+
f"Unable to extract neither project.version nor tool.poetry.version "
|
|
74
|
+
f" from {settings.pyproject_toml_path}"
|
|
75
|
+
)
|
|
76
|
+
raise ValueError(errmsg)
|
|
77
|
+
|
|
78
|
+
version.bump_release()
|
|
79
|
+
__save_version(pyproject_toml_path=settings.pyproject_toml_path, version=version)
|
|
80
|
+
__output(settings=settings, versions={"version": str(version)})
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def set_command(settings: argparse.Namespace) -> None:
|
|
84
|
+
"""
|
|
85
|
+
A version consists of several parts: epoch, major, minor, patch, release, a, b, rc, post, dev, and local.
|
|
86
|
+
This method allows setting any of the individual parts.
|
|
87
|
+
"""
|
|
88
|
+
version: Version | None = __load_version(settings)
|
|
89
|
+
if version is None:
|
|
90
|
+
errmsg = (
|
|
91
|
+
f"Unable to extract neither project.version nor tool.poetry.version "
|
|
92
|
+
f" from {settings.pyproject_toml_path}"
|
|
93
|
+
)
|
|
94
|
+
raise ValueError(errmsg)
|
|
95
|
+
|
|
96
|
+
version.set(part=settings.part, value=settings.value, clear_right=settings.clear_right)
|
|
97
|
+
__save_version(pyproject_toml_path=settings.pyproject_toml_path, version=version)
|
|
98
|
+
__output(settings=settings, versions={"version": str(version)})
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def __save_version(pyproject_toml_path: Path, version: Version) -> None:
|
|
102
|
+
"""
|
|
103
|
+
Saves the version to the pyproject.toml file. Always overwrites the project.version.
|
|
104
|
+
If the pyproject.toml file already has a tool.poetry.version, it will be overwritten,
|
|
105
|
+
but will not be created.
|
|
106
|
+
"""
|
|
107
|
+
# if tool.poetry.version exists, then overwrite it
|
|
108
|
+
versions: list[Version | None] = PyProject.load_version(
|
|
109
|
+
pyproject_toml_path=pyproject_toml_path, key_dot_notation_list=["tool.poetry.version"]
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
keys = ["project.version"]
|
|
113
|
+
if versions[0] is not None:
|
|
114
|
+
# only update tool.poetry.version, i.e. DO NOT CREATE
|
|
115
|
+
keys.append("tool.poetry.version")
|
|
116
|
+
|
|
117
|
+
# always save to project.version
|
|
118
|
+
PyProject.save_version(pyproject_toml_path=pyproject_toml_path, key_dot_notation_list=keys, version=version)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def __sanity_check_loaded_versions(project_version: Version | None, poetry_version: Version | None) -> Version | None:
|
|
122
|
+
"""
|
|
123
|
+
A pyproject.toml file must contain project.version and optionally tool.poetry.version.
|
|
124
|
+
This method returns the project version and will raise ValueError if tool.poetry.version exists and doesn't
|
|
125
|
+
match the project.version.
|
|
126
|
+
"""
|
|
127
|
+
if poetry_version is not None and project_version != poetry_version:
|
|
128
|
+
errmsg = f"project.version {project_version!s} does not match tool.poetry.version {poetry_version!s}"
|
|
129
|
+
raise ValueError(errmsg)
|
|
130
|
+
return project_version
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def __load_version(settings: argparse.Namespace) -> Version | None:
|
|
134
|
+
"""
|
|
135
|
+
Loads the version from the pyproject.toml file.
|
|
136
|
+
"""
|
|
137
|
+
# try to load both project.version and tool.poetry.version
|
|
138
|
+
versions: list[Version | None] = PyProject.load_version(
|
|
139
|
+
pyproject_toml_path=settings.pyproject_toml_path,
|
|
140
|
+
key_dot_notation_list=["project.version", "tool.poetry.version"],
|
|
141
|
+
)
|
|
142
|
+
# sanity check what we loaded
|
|
143
|
+
return __sanity_check_loaded_versions(versions[0], versions[1])
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def __output(settings: argparse.Namespace, versions: dict[str, str]) -> None:
|
|
147
|
+
"""
|
|
148
|
+
Formats and outputs the version(s) to the logger. The supported formats are:
|
|
149
|
+
--json, --text, and default, where default is human-readable meant for the console.
|
|
150
|
+
"""
|
|
151
|
+
if settings.json:
|
|
152
|
+
logger.info(json.dumps(versions))
|
|
153
|
+
elif settings.text:
|
|
154
|
+
logger.info("\n".join([str(versions[key]) for key in versions]))
|
|
155
|
+
else:
|
|
156
|
+
for key, value in versions.items():
|
|
157
|
+
logger.info(f"{key}: {value}")
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2024 Roy Wright
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import tempfile
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import tomlkit
|
|
12
|
+
from tomlkit import TOMLDocument
|
|
13
|
+
|
|
14
|
+
from version_bumper.version import Version
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class PyProject:
|
|
18
|
+
@classmethod
|
|
19
|
+
def load_version(cls, pyproject_toml_path: Path, key_dot_notation_list: list[str]) -> list[Version | None]:
|
|
20
|
+
"""
|
|
21
|
+
Load the versions specified by a list of dotted keys from the pyproject.toml file.
|
|
22
|
+
"""
|
|
23
|
+
versions: list[Version | None] = []
|
|
24
|
+
with pyproject_toml_path.open(encoding="utf-8") as f:
|
|
25
|
+
doc: TOMLDocument = tomlkit.load(f)
|
|
26
|
+
for key_dot_notation in key_dot_notation_list:
|
|
27
|
+
field: Any = doc
|
|
28
|
+
for key in key_dot_notation.split("."):
|
|
29
|
+
field = field.get(key)
|
|
30
|
+
versions.append(Version(field) if field is not None else None)
|
|
31
|
+
return versions
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def save_version(cls, pyproject_toml_path: Path, key_dot_notation_list: list[str], version: Version) -> None:
|
|
35
|
+
"""
|
|
36
|
+
Save the version to each of the dotted keys in the given list to the pyproject.toml file.
|
|
37
|
+
"""
|
|
38
|
+
with pyproject_toml_path.open(encoding="utf-8") as f:
|
|
39
|
+
doc: TOMLDocument = tomlkit.load(f)
|
|
40
|
+
for key_dot_notation in key_dot_notation_list:
|
|
41
|
+
field: Any = doc
|
|
42
|
+
for key in key_dot_notation.split(".")[:-1]:
|
|
43
|
+
field = field.get(key)
|
|
44
|
+
field.update({"version": str(version)})
|
|
45
|
+
|
|
46
|
+
# write to temporary file then atomically "switch" it with the original using rename.
|
|
47
|
+
with tempfile.NamedTemporaryFile("wt", dir=pyproject_toml_path.parent, delete=False) as tf:
|
|
48
|
+
tf.write(tomlkit.dumps(doc))
|
|
49
|
+
temp_name = Path(tf.name)
|
|
50
|
+
temp_name.rename(pyproject_toml_path)
|