-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuilder.py
More file actions
483 lines (379 loc) · 16.5 KB
/
builder.py
File metadata and controls
483 lines (379 loc) · 16.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
"""Defines the data and routines for building a CPPython project type"""
import logging
import os
from importlib.metadata import entry_points
from inspect import getmodule
from logging import Logger
from pathlib import Path
from pprint import pformat
from typing import Any, cast
from rich.console import Console
from rich.logging import RichHandler
from cppython.configuration import ConfigurationLoader
from cppython.core.plugin_schema.generator import Generator
from cppython.core.plugin_schema.provider import Provider
from cppython.core.plugin_schema.scm import SCM, SupportedSCMFeatures
from cppython.core.resolution import (
PluginBuildData,
PluginCPPythonData,
resolve_cppython,
resolve_cppython_plugin,
resolve_generator,
resolve_model,
resolve_pep621,
resolve_project_configuration,
resolve_provider,
resolve_scm,
)
from cppython.core.schema import (
CoreData,
CorePluginData,
CPPythonGlobalConfiguration,
CPPythonLocalConfiguration,
DataPlugin,
PEP621Configuration,
PEP621Data,
Plugin,
ProjectConfiguration,
ProjectData,
)
from cppython.data import Data, Plugins
from cppython.defaults import DefaultSCM
from cppython.utility.exception import PluginError
from cppython.utility.utility import TypeName
class Resolver:
"""The resolution of data sources for the builder"""
def __init__(self, project_configuration: ProjectConfiguration, logger: Logger) -> None:
"""Initializes the resolver"""
self._project_configuration = project_configuration
self._logger = logger
def generate_plugins(
self, cppython_local_configuration: CPPythonLocalConfiguration, project_data: ProjectData
) -> PluginBuildData:
"""Generates the plugin data from the local configuration and project data
Args:
cppython_local_configuration: The local configuration
project_data: The project data
Returns:
The resolved plugin data
"""
raw_generator_plugins = self._find_plugins('generator', Generator)
generator_plugins = self.filter_plugins(
raw_generator_plugins,
self._get_effective_plugin_name(cppython_local_configuration.generators),
'Generator',
)
raw_provider_plugins = self._find_plugins('provider', Provider)
provider_plugins = self.filter_plugins(
raw_provider_plugins,
self._get_effective_plugin_name(cppython_local_configuration.providers),
'Provider',
)
scm_plugins = self._find_plugins('scm', SCM)
scm_type = self.select_scm(scm_plugins, project_data)
# Solve the messy interactions between plugins
generator_type, provider_type = self.solve(generator_plugins, provider_plugins)
return PluginBuildData(generator_type=generator_type, provider_type=provider_type, scm_type=scm_type)
@staticmethod
def _get_effective_plugin_name(plugins: dict[TypeName, Any]) -> str | None:
"""Get the effective plugin name from a plugins configuration dict.
Args:
plugins: The plugins dict (e.g. config.generators or config.providers)
Returns:
The first plugin name if any are configured, or None for auto-detection
"""
if plugins:
return list(plugins.keys())[0]
return None
@staticmethod
def get_plugin_config(plugins: dict[TypeName, Any], plugin_name: str) -> dict[str, Any]:
"""Get the configuration dict for a specific plugin.
Args:
plugins: The plugins dict (e.g. config.generators or config.providers)
plugin_name: The name of the plugin
Returns:
The configuration dict for the plugin, or empty dict if not found
"""
type_name = TypeName(plugin_name)
if type_name in plugins:
return plugins[type_name]
return {}
@staticmethod
def generate_cppython_plugin_data(plugin_build_data: PluginBuildData) -> PluginCPPythonData:
"""Generates the CPPython plugin data from the resolved plugins
Args:
plugin_build_data: The resolved plugin data
Returns:
The plugin data used by CPPython
"""
return PluginCPPythonData(
generator_name=plugin_build_data.generator_type.name(),
provider_name=plugin_build_data.provider_type.name(),
scm_name=plugin_build_data.scm_type.name(),
)
@staticmethod
def generate_pep621_data(
pep621_configuration: PEP621Configuration, project_configuration: ProjectConfiguration, scm: SCM | None
) -> PEP621Data:
"""Generates the PEP621 data from configuration sources
Args:
pep621_configuration: The PEP621 configuration
project_configuration: The project configuration
scm: The source control manager, if any
Returns:
The resolved PEP621 data
"""
return resolve_pep621(pep621_configuration, project_configuration, scm)
@staticmethod
def resolve_global_config() -> CPPythonGlobalConfiguration:
"""Generates the global configuration object by loading from ~/.cppython/config.toml
Returns:
The global configuration object with loaded or default values
"""
loader = ConfigurationLoader(Path.cwd())
try:
global_config_data = loader.load_global_config()
if global_config_data:
return resolve_model(CPPythonGlobalConfiguration, global_config_data)
except FileNotFoundError, ValueError:
# If global config doesn't exist or is invalid, use defaults
pass
return CPPythonGlobalConfiguration()
def _find_plugins[T: Plugin](self, group_name: str, base_type: type[T]) -> list[type[T]]:
"""Extracts plugins of a given type from entry points.
Args:
group_name: The entry point group suffix (e.g. 'generator', 'provider', 'scm')
base_type: The expected base type to filter against
Raises:
PluginError: Raised if no plugins can be found
Returns:
The list of discovered plugin types
"""
plugin_types: list[type[T]] = []
entries = entry_points(group=f'cppython.{group_name}')
for entry_point in list(entries):
loaded_type = entry_point.load()
if not issubclass(loaded_type, base_type):
self._logger.warning(
f"Found incompatible plugin. The '{loaded_type.name()}' plugin must be an instance of"
f" '{group_name}'"
)
else:
self._logger.info(f'{group_name} plugin found: {loaded_type.name()} from {getmodule(loaded_type)}')
plugin_types.append(loaded_type)
if not plugin_types:
raise PluginError(f'No {group_name} plugin was found')
return plugin_types
def filter_plugins[T: DataPlugin](
self, plugin_types: list[type[T]], pinned_name: str | None, group_name: str
) -> list[type[T]]:
"""Finds and filters data plugins
Args:
plugin_types: The plugin type to lookup
pinned_name: The configuration name
group_name: The group name
Raises:
PluginError: Raised if no plugins can be found
Returns:
The list of applicable plugins
"""
# Lookup the requested plugin if given
if pinned_name is not None:
for loaded_type in plugin_types:
if loaded_type.name() == pinned_name:
self._logger.info(f'Using {group_name} plugin: {loaded_type.name()} from {getmodule(loaded_type)}')
return [loaded_type]
self._logger.info(f"'{group_name}_name' was empty. Trying to deduce {group_name}s")
supported_types: list[type[T]] = []
# Deduce types
for loaded_type in plugin_types:
self._logger.info(f'A {group_name} plugin is supported: {loaded_type.name()} from {getmodule(loaded_type)}')
supported_types.append(loaded_type)
# Fail
if supported_types is None:
raise PluginError(f'No {group_name} could be deduced from the root directory.')
return supported_types
def select_scm(self, scm_plugins: list[type[SCM]], project_data: ProjectData) -> type[SCM]:
"""Given data constraints, selects the SCM plugin to use
Args:
scm_plugins: The list of SCM plugin types
project_data: The project data
Returns:
The selected SCM plugin type
"""
for scm_type in scm_plugins:
if cast(SupportedSCMFeatures, scm_type.features(project_data.project_root)).repository:
return scm_type
self._logger.info('No SCM plugin was found that supports the given path')
return DefaultSCM
@staticmethod
def solve(
generator_types: list[type[Generator]], provider_types: list[type[Provider]]
) -> tuple[type[Generator], type[Provider]]:
"""Selects the first generator and provider that can work together
Args:
generator_types: The list of generator plugin types
provider_types: The list of provider plugin types
Raises:
PluginError: Raised if no provider that supports a given generator could be deduced
Returns:
A tuple of the selected generator and provider plugin types
"""
combos: list[tuple[type[Generator], type[Provider]]] = []
for generator_type in generator_types:
sync_types = generator_type.sync_types()
for provider_type in provider_types:
for sync_type in sync_types:
if provider_type.supported_sync_type(sync_type):
combos.append((generator_type, provider_type))
break
if not combos:
raise PluginError('No provider that supports a given generator could be deduced')
return combos[0]
@staticmethod
def create_scm[T: SCM](
core_data: CoreData,
scm_type: type[T],
) -> T:
"""Creates a source control manager from input configuration
Args:
core_data: The resolved configuration data
scm_type: The plugin type
Returns:
The constructed source control manager
"""
cppython_plugin_data = resolve_cppython_plugin(core_data.cppython_data, scm_type)
scm_data = resolve_scm(core_data.project_data, cppython_plugin_data)
plugin = scm_type(scm_data)
return plugin
def create_generator[T: Generator](
self,
core_data: CoreData,
pep621_data: PEP621Data,
generator_configuration: dict[str, Any],
generator_type: type[T],
) -> T:
"""Creates a generator from input configuration
Args:
core_data: The resolved configuration data
pep621_data: The PEP621 data
generator_configuration: The generator table of the CPPython configuration data
generator_type: The plugin type
Returns:
The constructed generator
"""
cppython_plugin_data = resolve_cppython_plugin(core_data.cppython_data, generator_type)
generator_data = resolve_generator(core_data.project_data, cppython_plugin_data)
if not generator_configuration:
self._logger.info(
"The pyproject.toml table 'tool.cppython.generator' does not exist. Sending generator empty data",
)
core_plugin_data = CorePluginData(
project_data=core_data.project_data,
pep621_data=pep621_data,
cppython_data=cppython_plugin_data,
)
return generator_type(generator_data, core_plugin_data, generator_configuration)
def create_provider[T: Provider](
self,
core_data: CoreData,
pep621_data: PEP621Data,
provider_configuration: dict[str, Any],
provider_type: type[T],
) -> T:
"""Creates Providers from input data
Args:
core_data: The resolved configuration data
pep621_data: The PEP621 data
provider_configuration: The provider data table
provider_type: The type to instantiate
Returns:
A constructed provider plugins
"""
cppython_plugin_data = resolve_cppython_plugin(core_data.cppython_data, provider_type)
provider_data = resolve_provider(core_data.project_data, cppython_plugin_data)
if not provider_configuration:
self._logger.info(
"The pyproject.toml table 'tool.cppython.provider' does not exist. Sending provider empty data",
)
core_plugin_data = CorePluginData(
project_data=core_data.project_data,
pep621_data=pep621_data,
cppython_data=cppython_plugin_data,
)
return provider_type(provider_data, core_plugin_data, provider_configuration)
class Builder:
"""Helper class for building CPPython projects"""
levels = [logging.WARNING, logging.INFO, logging.DEBUG]
def __init__(self, project_configuration: ProjectConfiguration, logger: Logger) -> None:
"""Initializes the builder"""
self._project_configuration = project_configuration
self._logger = logger
# Informal standard to check for color
force_color = os.getenv('FORCE_COLOR', '1') != '0'
self._console = Console(
force_terminal=force_color,
color_system='auto',
width=120,
legacy_windows=False,
no_color=False,
)
rich_handler = RichHandler(
console=self._console,
rich_tracebacks=True,
show_time=False,
show_path=False,
markup=True,
show_level=False,
enable_link_path=False,
)
self._logger.addHandler(rich_handler)
self._logger.setLevel(Builder.levels[project_configuration.verbosity])
self._logger.info('Logging setup complete')
self._resolver = Resolver(self._project_configuration, self._logger)
@property
def console(self) -> Console:
"""The Rich console instance used for terminal output."""
return self._console
def build(
self,
pep621_configuration: PEP621Configuration,
cppython_local_configuration: CPPythonLocalConfiguration,
plugin_build_data: PluginBuildData | None = None,
) -> Data:
"""Builds the project data
Args:
pep621_configuration: The PEP621 configuration
cppython_local_configuration: The local configuration
plugin_build_data: Plugin override data. If it exists, the build will use the given types
instead of resolving them
Returns:
The built data object
"""
project_data = resolve_project_configuration(self._project_configuration)
if plugin_build_data is None:
plugin_build_data = self._resolver.generate_plugins(cppython_local_configuration, project_data)
plugin_cppython_data = self._resolver.generate_cppython_plugin_data(plugin_build_data)
global_configuration = self._resolver.resolve_global_config()
cppython_data = resolve_cppython(
cppython_local_configuration, global_configuration, project_data, plugin_cppython_data
)
core_data = CoreData(project_data=project_data, cppython_data=cppython_data)
scm = self._resolver.create_scm(core_data, plugin_build_data.scm_type)
pep621_data = self._resolver.generate_pep621_data(pep621_configuration, self._project_configuration, scm)
# Create the chosen plugins
generator_config = Resolver.get_plugin_config(
cppython_local_configuration.generators, plugin_build_data.generator_type.name()
)
generator = self._resolver.create_generator(
core_data, pep621_data, generator_config, plugin_build_data.generator_type
)
provider_config = Resolver.get_plugin_config(
cppython_local_configuration.providers, plugin_build_data.provider_type.name()
)
provider = self._resolver.create_provider(
core_data, pep621_data, provider_config, plugin_build_data.provider_type
)
plugins = Plugins(generator=generator, provider=provider, scm=scm)
self._logger.debug('Project data:\n%s', pformat(dict(core_data)))
return Data(core_data, plugins, self._logger)