-
-
Notifications
You must be signed in to change notification settings - Fork 334
Expand file tree
/
Copy pathbase_provider.py
More file actions
100 lines (71 loc) · 2.63 KB
/
base_provider.py
File metadata and controls
100 lines (71 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
from __future__ import annotations
import json
from abc import ABC, abstractmethod
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar
import tomlkit
if TYPE_CHECKING:
from collections.abc import Mapping
from commitizen.config.base_config import BaseConfig
class VersionProvider(ABC):
"""
Abstract base class for version providers.
Each version provider should inherit and implement this class.
"""
config: BaseConfig
def __init__(self, config: BaseConfig) -> None:
self.config = config
@abstractmethod
def get_version(self) -> str:
"""
Get the current version
"""
@abstractmethod
def set_version(self, version: str) -> None:
"""
Set the new current version
"""
class FileProvider(VersionProvider):
"""
Base class for file-based version providers
"""
filename: ClassVar[str]
@property
def file(self) -> Path:
return Path() / self.filename
def _get_encoding(self) -> str:
return self.config.settings["encoding"]
class JsonProvider(FileProvider):
"""
Base class for JSON-based version providers
"""
indent: ClassVar[int] = 2
def get_version(self) -> str:
document = json.loads(self.file.read_text(encoding=self._get_encoding()))
return self.get(document)
def set_version(self, version: str) -> None:
document = json.loads(self.file.read_text(encoding=self._get_encoding()))
self.set(document, version)
self.file.write_text(
json.dumps(document, indent=self.indent) + "\n",
encoding=self._get_encoding(),
)
def get(self, document: Mapping[str, str]) -> str:
return document["version"]
def set(self, document: dict[str, Any], version: str) -> None:
document["version"] = version
class TomlProvider(FileProvider):
"""
Base class for TOML-based version providers
"""
def get_version(self) -> str:
document = tomlkit.parse(self.file.read_text(encoding=self._get_encoding()))
return self.get(document)
def set_version(self, version: str) -> None:
document = tomlkit.parse(self.file.read_text(encoding=self._get_encoding()))
self.set(document, version)
self.file.write_text(tomlkit.dumps(document), encoding=self._get_encoding())
def get(self, document: tomlkit.TOMLDocument) -> str:
return document["project"]["version"] # type: ignore # noqa: PGH003
def set(self, document: tomlkit.TOMLDocument, version: str) -> None:
document["project"]["version"] = version # type: ignore # noqa: PGH003