forked from synodic/cppython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.py
More file actions
422 lines (311 loc) · 13.5 KB
/
schema.py
File metadata and controls
422 lines (311 loc) · 13.5 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
"""Data types for CPPython that encapsulate the requirements between the plugins and the core library"""
from abc import abstractmethod
from pathlib import Path
from typing import Annotated, Any, NewType, Protocol, Self, runtime_checkable
from packaging.requirements import Requirement
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from pydantic.types import DirectoryPath
from cppython.utility.plugin import Plugin as SynodicPlugin
from cppython.utility.utility import TypeName
class CPPythonModel(BaseModel):
"""The base model to use for all CPPython models"""
model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, arbitrary_types_allowed=True)
class ProjectData(CPPythonModel, extra='forbid'):
"""Resolved data of 'ProjectConfiguration'"""
project_root: Annotated[Path, Field(description='The path where the pyproject.toml exists')]
verbosity: Annotated[int, Field(description='The verbosity level as an integer [0,2]')] = 0
class ProjectConfiguration(CPPythonModel, extra='forbid'):
"""Project-wide configuration"""
project_root: Annotated[Path, Field(description='The path where the pyproject.toml exists')]
version: Annotated[
str | None,
Field(
description=(
"The version number a 'dynamic' project version will resolve to. If not provided"
'a CPPython project will'
' initialize its SCM plugins to discover any available version'
)
),
]
verbosity: Annotated[int, Field(description='The verbosity level as an integer [0,2]')] = 0
debug: Annotated[
bool, Field(description='Debug mode. Additional processing will happen to expose more debug information')
] = False
@field_validator('verbosity')
@classmethod
def min_max(cls, value: int) -> int:
"""Validator that clamps the input value
Args:
value: Input to validate
Returns:
The clamped input value
"""
return min(max(value, 0), 2)
class PEP621Data(CPPythonModel):
"""Resolved PEP621Configuration data"""
name: str
version: str
description: str
class PEP621Configuration(CPPythonModel):
"""CPPython relevant PEP 621 conforming data
Because only the partial schema is used, we ignore 'extra' attributes
Schema: https://www.python.org/dev/peps/pep-0621/
"""
dynamic: Annotated[list[str], Field(description='https://peps.python.org/pep-0621/#dynamic')] = []
name: Annotated[str, Field(description='https://peps.python.org/pep-0621/#name')]
version: Annotated[str | None, Field(description='https://peps.python.org/pep-0621/#version')] = None
description: Annotated[str, Field(description='https://peps.python.org/pep-0621/#description')] = ''
@model_validator(mode='after') # type: ignore
@classmethod
def dynamic_data(cls, model: Self) -> Self:
"""Validates that dynamic data is represented correctly
Args:
model: The input model data
Raises:
ValueError: If dynamic versioning is incorrect
Returns:
The data
"""
for field in PEP621Configuration.model_fields:
if field == 'dynamic':
continue
value = getattr(model, field)
if field not in model.dynamic:
if value is None:
raise ValueError(f"'{field}' is not a dynamic field. It must be defined")
elif value is not None:
raise ValueError(f"'{field}' is a dynamic field. It must not be defined")
return model
class CPPythonData(CPPythonModel, extra='forbid'):
"""Resolved CPPython data with local and global configuration"""
configuration_path: Path
install_path: Path
tool_path: Path
build_path: Path
current_check: bool
provider_name: TypeName
generator_name: TypeName
scm_name: TypeName
dependencies: list[Requirement]
dependency_groups: dict[str, list[Requirement]]
provider_data: Annotated[dict[str, Any], Field(description='Resolved provider configuration data')]
generator_data: Annotated[dict[str, Any], Field(description='Resolved generator configuration data')]
@field_validator('configuration_path', 'install_path', 'tool_path', 'build_path')
@classmethod
def validate_absolute_path(cls, value: Path) -> Path:
"""Enforce the input is an absolute path
Args:
value: The input value
Raises:
ValueError: Raised if the input is not an absolute path
Returns:
The validated input value
"""
if not value.is_absolute():
raise ValueError('Absolute path required')
return value
CPPythonPluginData = NewType('CPPythonPluginData', CPPythonData)
class PluginReport(CPPythonModel):
"""Report returned by a data plugin's ``plugin_info()`` method.
Contains the plugin's current configuration, any managed files it writes,
and the content of user-facing template files it can generate.
"""
configuration: Annotated[
dict[str, Any],
Field(description='Key-value pairs of the resolved plugin configuration'),
] = {}
managed_files: Annotated[
list[Path],
Field(description='Paths to files that are fully managed (auto-generated) by the plugin'),
] = []
template_files: Annotated[
dict[str, str],
Field(description='Mapping of template file names to their current content'),
] = {}
class SyncData(CPPythonModel):
"""Data that passes in a plugin sync"""
provider_name: TypeName
class SupportedFeatures(CPPythonModel):
"""Plugin feature support"""
initialization: Annotated[
bool, Field(description='Whether the plugin supports initialization from an empty state')
] = False
class Information(CPPythonModel):
"""Plugin information that complements the packaged project metadata"""
class PluginGroupData(CPPythonModel, extra='forbid'):
"""Plugin group data"""
root_directory: Annotated[DirectoryPath, Field(description='The directory of the project')]
tool_directory: Annotated[
Path,
Field(
description=(
'Points to the project plugin directory within the tool directory. '
'This directory is for project specific cached data.'
)
),
]
class Plugin(SynodicPlugin, Protocol):
"""CPPython plugin"""
@abstractmethod
def __init__(self, group_data: PluginGroupData) -> None:
"""Initializes the plugin"""
raise NotImplementedError
@staticmethod
@abstractmethod
def features(directory: DirectoryPath) -> SupportedFeatures:
"""Broadcasts the shared features of the plugin to CPPython
Args:
directory: The root directory where features are evaluated
Returns:
The supported features
"""
raise NotImplementedError
@staticmethod
@abstractmethod
def information() -> Information:
"""Retrieves plugin information that complements the packaged project metadata
Returns:
The plugin's information
"""
raise NotImplementedError
class DataPluginGroupData(PluginGroupData):
"""Data plugin group data"""
class CorePluginData(CPPythonModel):
"""Core resolved data that will be passed to data plugins"""
project_data: ProjectData
pep621_data: PEP621Data
cppython_data: CPPythonPluginData
class SupportedDataFeatures(SupportedFeatures):
"""Data plugin feature support"""
class DataPlugin(Plugin, Protocol):
"""Abstract plugin type for internal CPPython data"""
@abstractmethod
def __init__(
self, group_data: DataPluginGroupData, core_data: CorePluginData, configuration_data: dict[str, Any]
) -> None:
"""Initializes the data plugin"""
raise NotImplementedError
@staticmethod
@abstractmethod
def features(directory: DirectoryPath) -> SupportedFeatures:
"""Broadcasts the shared features of the data plugin to CPPython
Args:
directory: The root directory where features are evaluated
Returns:
The supported features - `SupportedDataFeatures`. Cast to this type to help us avoid generic typing
"""
raise NotImplementedError
def plugin_info(self) -> PluginReport:
"""Return a report describing this plugin's configuration, managed files, and templates.
Plugins should override this method to provide meaningful information.
The default implementation returns an empty report.
Returns:
A :class:`PluginReport` with plugin-specific details.
"""
return PluginReport()
@classmethod
async def download_tooling(cls, directory: DirectoryPath) -> None:
"""Installs the external tooling required by the plugin. Should be overridden if required
Args:
directory: The directory to download any extra tooling to
"""
class CPPythonGlobalConfiguration(CPPythonModel, extra='forbid'):
"""Global data extracted by the tool"""
current_check: Annotated[bool, Field(alias='current-check', description='Checks for a new CPPython version')] = True
ProviderData = NewType('ProviderData', dict[str, Any])
GeneratorData = NewType('GeneratorData', dict[str, Any])
class CPPythonLocalConfiguration(CPPythonModel, extra='forbid'):
"""Project-level CPPython configuration
This configuration is stored in pyproject.toml or cppython.toml.
User-specific overrides can be placed in .cppython.toml (which should be gitignored).
"""
configuration_path: Annotated[
Path | None,
Field(
description='The path to the configuration override file. If present, configuration found in the given'
' directory will be preferred'
),
] = None
install_path: Annotated[
Path,
Field(
alias='install-path',
description='The global install path for the project. Provider and generator plugins will be'
' installed here.',
),
] = Path.home() / '.cppython'
tool_path: Annotated[
Path,
Field(
alias='tool-path',
description='The local tooling path for the project. If the provider or generator need additional file'
' support, this directory will be used',
),
] = Path('tool')
build_path: Annotated[
Path,
Field(
alias='build-path',
description='The local build path for the project. This is where the artifacts of the local C++ build'
' process will be generated.',
),
] = Path('build')
providers: Annotated[
dict[TypeName, ProviderData],
Field(
description='Named provider configurations. Key is the provider name, value is the provider configuration.'
),
] = {}
generators: Annotated[
dict[TypeName, GeneratorData],
Field(
description=(
'Named generator configurations. Key is the generator name, value is the generator configuration.'
)
),
] = {}
dependencies: Annotated[
list[str] | None,
Field(
description='A list of dependencies that will be installed. This is a list of pip compatible requirements'
' strings',
),
] = None
dependency_groups: Annotated[
dict[str, list[str]] | None,
Field(
alias='dependency-groups',
description='Named groups of dependencies. Key is the group name, value is a list of pip compatible'
' requirements strings. Similar to PEP 735 dependency groups.',
),
] = None
class ToolData(CPPythonModel):
"""Tool entry of pyproject.toml"""
cppython: Annotated[CPPythonLocalConfiguration | None, Field(description='CPPython tool data')] = None
class PyProject(CPPythonModel):
"""pyproject.toml schema"""
project: Annotated[PEP621Configuration, Field(description='PEP621: https://www.python.org/dev/peps/pep-0621/')]
tool: Annotated[ToolData | None, Field(description='Tool data')] = None
class CoreData(CPPythonModel):
"""Core resolved data that will be resolved"""
project_data: ProjectData
cppython_data: CPPythonData
@runtime_checkable
class Interface(Protocol):
"""Type for interfaces to allow feedback from CPPython"""
@abstractmethod
def write_pyproject(self) -> None:
"""Called when CPPython requires the interface to write out pyproject.toml changes"""
raise NotImplementedError
@abstractmethod
def write_configuration(self) -> None:
"""Called when CPPython requires the interface to write out configuration changes
This writes to the primary configuration source (pyproject.toml or cppython.toml)
"""
raise NotImplementedError
@abstractmethod
def write_user_configuration(self) -> None:
"""Called when CPPython requires the interface to write out global configuration changes
This writes to ~/.cppython/config.toml for global user configuration
"""
raise NotImplementedError