-
Notifications
You must be signed in to change notification settings - Fork 255
/
Copy pathtoml.py
106 lines (76 loc) · 2.95 KB
/
toml.py
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
101
102
103
104
105
106
from __future__ import annotations
from typing import TYPE_CHECKING
from typing import Any
if TYPE_CHECKING:
from pathlib import Path
from tomlkit.container import Container
from tomlkit.items import Item
from tomlkit.toml_document import TOMLDocument
from poetry.core.pyproject.tables import BuildSystem
from poetry.core.toml import TOMLFile
class PyProjectTOML:
def __init__(self, path: str | Path) -> None:
from poetry.core.toml import TOMLFile
self._file = TOMLFile(path=path)
self._data: TOMLDocument | None = None
self._build_system: BuildSystem | None = None
@property
def file(self) -> TOMLFile:
return self._file
@property
def data(self) -> TOMLDocument:
from tomlkit.toml_document import TOMLDocument
if self._data is None:
if not self._file.exists():
self._data = TOMLDocument()
else:
self._data = self._file.read()
return self._data
@property
def build_system(self) -> BuildSystem:
from poetry.core.pyproject.tables import BuildSystem
if self._build_system is None:
build_backend = None
requires = None
if not self._file.exists():
build_backend = "poetry.core.masonry.api"
requires = ["poetry-core"]
container = self.data.get("build-system", {})
self._build_system = BuildSystem(
build_backend=container.get("build-backend", build_backend),
requires=container.get("requires", requires),
)
return self._build_system
@property
def poetry_config(self) -> Item | Container:
from tomlkit.exceptions import NonExistentKey
try:
return self.data["tool"]["poetry"]
except NonExistentKey as e:
from poetry.core.pyproject.exceptions import PyProjectException
raise PyProjectException(
f"[tool.poetry] section not found in {self._file}"
) from e
def is_poetry_project(self) -> bool:
from poetry.core.pyproject.exceptions import PyProjectException
if self.file.exists():
try:
_ = self.poetry_config
return True
except PyProjectException:
pass
return False
def __getattr__(self, item: str) -> Any:
return getattr(self.data, item)
def save(self) -> None:
from tomlkit.container import Container
data = self.data
if self._build_system is not None:
if "build-system" not in data:
data["build-system"] = Container()
data["build-system"]["requires"] = self._build_system.requires
data["build-system"]["build-backend"] = self._build_system.build_backend
self.file.write(data=data)
def reload(self) -> None:
self._data = None
self._build_system = None