-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathentry.py
More file actions
411 lines (320 loc) · 11.8 KB
/
entry.py
File metadata and controls
411 lines (320 loc) · 11.8 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
"""A Typer CLI for CPPython interfacing"""
import contextlib
from collections.abc import Generator
from importlib.metadata import entry_points
from pathlib import Path
from typing import Annotated
import typer
from rich import print
from rich.console import Console
from rich.syntax import Syntax
from cppython.configuration import ConfigurationLoader
from cppython.console.schema import ConsoleConfiguration, ConsoleInterface
from cppython.core.schema import PluginReport, ProjectConfiguration
from cppython.project import Project
from cppython.utility.output import OutputSession
app = typer.Typer(no_args_is_help=True)
info_app = typer.Typer(
no_args_is_help=True,
help='Prints project information including plugin configuration, managed files, and templates.',
)
app.add_typer(info_app, name='info')
list_app = typer.Typer(no_args_is_help=True, help='List project entities.')
app.add_typer(list_app, name='list')
def _get_configuration(context: typer.Context) -> ConsoleConfiguration:
"""Extract the ConsoleConfiguration object from the CLI context.
Raises:
ValueError: If the configuration object is missing
"""
configuration = context.find_object(ConsoleConfiguration)
if configuration is None:
raise ValueError('The configuration object is missing')
return configuration
def get_enabled_project(context: typer.Context) -> Project:
"""Helper to load and validate an enabled Project from CLI context."""
configuration = _get_configuration(context)
# Use ConfigurationLoader to load and merge all configuration sources
loader = ConfigurationLoader(configuration.project_configuration.project_root)
pyproject_data = loader.get_project_data()
project = Project(configuration.project_configuration, configuration.interface, pyproject_data)
if not project.enabled:
print('[bold red]Error[/bold red]: Project is not enabled. Please check your configuration files.')
print('Configuration files checked:')
config_info = loader.config_source_info()
for config_file, exists in config_info.items():
status = '✓' if exists else '✗'
print(f' {status} {config_file}')
raise typer.Exit(code=1)
return project
@contextlib.contextmanager
def _session_project(context: typer.Context) -> Generator[Project]:
"""Create an enabled Project wrapped in an OutputSession.
Yields the project with its session already attached. The session
(spinner + log file) is torn down when the ``with`` block exits.
"""
project = get_enabled_project(context)
configuration = _get_configuration(context)
verbose = configuration.project_configuration.verbosity > 0
console = Console(width=120)
with OutputSession(console, verbose=verbose) as session:
project.session = session
yield project
def _parse_groups_argument(groups: str | None) -> list[str] | None:
"""Parse pip-style dependency groups from command argument.
Args:
groups: Groups string like '[test]' or '[dev,test]' or None
Returns:
List of group names or None if no groups specified
Raises:
typer.BadParameter: If the groups format is invalid
"""
if groups is None:
return None
# Strip whitespace
groups = groups.strip()
if not groups:
return None
# Check for square brackets
if not (groups.startswith('[') and groups.endswith(']')):
raise typer.BadParameter(f"Invalid groups format: '{groups}'. Use square brackets like: [test] or [dev,test]")
# Extract content between brackets and split by comma
content = groups[1:-1].strip()
if not content:
raise typer.BadParameter('Empty groups specification. Provide at least one group name.')
# Split by comma and strip whitespace from each group
group_list = [g.strip() for g in content.split(',')]
# Validate group names are not empty
if any(not g for g in group_list):
raise typer.BadParameter('Group names cannot be empty.')
return group_list
def _find_pyproject_file() -> Path:
"""Searches upward for a pyproject.toml file.
Returns:
The directory containing pyproject.toml
Raises:
AssertionError: If no pyproject.toml is found up to the filesystem root
"""
path = Path.cwd()
while True:
if (path / 'pyproject.toml').exists():
return path
parent = path.parent
if parent == path:
raise AssertionError(
'This is not a valid project. No pyproject.toml found in the current directory or any of its parents.'
)
path = parent
@app.callback()
def main(
context: typer.Context,
verbose: Annotated[
int, typer.Option('-v', '--verbose', count=True, min=0, max=2, help='Print additional output')
] = 0,
debug: Annotated[bool, typer.Option()] = False,
) -> None:
"""entry_point group for the CLI commands
Args:
context: The typer context
verbose: The verbosity level
debug: Debug mode
"""
path = _find_pyproject_file()
project_configuration = ProjectConfiguration(verbosity=verbose, debug=debug, project_root=path, version=None)
interface = ConsoleInterface()
context.obj = ConsoleConfiguration(project_configuration=project_configuration, interface=interface)
def _print_plugin_report(role: str, name: str, report: PluginReport) -> None:
"""Print a single plugin's report to the console.
Args:
role: The plugin role label (e.g. 'Provider', 'Generator')
name: The plugin name
report: The plugin report to display
"""
print(f'\n[bold]{role}:[/bold] {name}')
if report.configuration:
print(' [bold]Configuration:[/bold]')
for key, value in report.configuration.items():
print(f' {key}: {value}')
if report.managed_files:
print(' [bold]Managed files:[/bold]')
for file_path in report.managed_files:
print(f' {file_path}')
if report.template_files:
print(' [bold]Templates:[/bold]')
for filename, content in report.template_files.items():
print(f' [cyan]{filename}[/cyan]')
print()
print(Syntax(content, 'python', theme='monokai', line_numbers=True))
@info_app.command()
def info_provider(
context: typer.Context,
) -> None:
"""Show provider plugin information."""
project = get_enabled_project(context)
project_info = project.info()
entry = project_info.get('provider')
if entry is None:
return
_print_plugin_report('Provider', entry['name'], entry['report'])
@info_app.command()
def info_generator(
context: typer.Context,
) -> None:
"""Show generator plugin information."""
project = get_enabled_project(context)
project_info = project.info()
entry = project_info.get('generator')
if entry is None:
return
_print_plugin_report('Generator', entry['name'], entry['report'])
@app.command()
def install(
context: typer.Context,
groups: Annotated[
str | None,
typer.Argument(
help='Dependency groups to install in addition to base dependencies. '
'Use square brackets like: [test] or [dev,test]'
),
] = None,
) -> None:
"""Install API call
Args:
context: The CLI configuration object
groups: Optional dependency groups to install (e.g., [test] or [dev,test])
Raises:
ValueError: If the configuration object is missing
"""
group_list = _parse_groups_argument(groups)
with _session_project(context) as project:
project.install(groups=group_list)
@app.command()
def update(
context: typer.Context,
groups: Annotated[
str | None,
typer.Argument(
help='Dependency groups to update in addition to base dependencies. '
'Use square brackets like: [test] or [dev,test]'
),
] = None,
) -> None:
"""Update API call
Args:
context: The CLI configuration object
groups: Optional dependency groups to update (e.g., [test] or [dev,test])
Raises:
ValueError: If the configuration object is missing
"""
group_list = _parse_groups_argument(groups)
with _session_project(context) as project:
project.update(groups=group_list)
@list_app.command()
def plugins() -> None:
"""List all installed CPPython plugins."""
groups = {
'Generators': 'cppython.generator',
'Providers': 'cppython.provider',
'SCM': 'cppython.scm',
}
for label, group in groups.items():
entries = entry_points(group=group)
print(f'\n[bold]{label}:[/bold]')
if not entries:
print(' (none installed)')
else:
for ep in sorted(entries, key=lambda e: e.name):
print(f' {ep.name}')
@list_app.command()
def targets(
context: typer.Context,
) -> None:
"""List discovered build targets."""
project = get_enabled_project(context)
target_list = project.list_targets()
if not target_list:
print('[dim]No targets found. Have you run install and build?[/dim]')
return
print('\n[bold]Targets:[/bold]')
for target_name in sorted(target_list):
print(f' {target_name}')
@app.command()
def publish(
context: typer.Context,
) -> None:
"""Publish API call
Args:
context: The CLI configuration object
Raises:
ValueError: If the configuration object is missing
"""
with _session_project(context) as project:
project.publish()
@app.command()
def build(
context: typer.Context,
configuration: Annotated[
str | None,
typer.Option(help='Named build configuration to use (e.g. CMake preset name, Meson build directory)'),
] = None,
) -> None:
"""Build the project
Assumes dependencies have been installed via `install`.
Args:
context: The CLI configuration object
configuration: Optional named configuration
"""
with _session_project(context) as project:
project.build(configuration=configuration)
@app.command()
def test(
context: typer.Context,
configuration: Annotated[
str | None,
typer.Option(help='Named build configuration to use (e.g. CMake preset name, Meson build directory)'),
] = None,
) -> None:
"""Run project tests
Assumes dependencies have been installed via `install`.
Args:
context: The CLI configuration object
configuration: Optional named configuration
"""
with _session_project(context) as project:
project.test(configuration=configuration)
@app.command()
def bench(
context: typer.Context,
configuration: Annotated[
str | None,
typer.Option(help='Named build configuration to use (e.g. CMake preset name, Meson build directory)'),
] = None,
) -> None:
"""Run project benchmarks
Assumes dependencies have been installed via `install`.
Args:
context: The CLI configuration object
configuration: Optional named configuration
"""
with _session_project(context) as project:
project.bench(configuration=configuration)
@app.command()
def run(
context: typer.Context,
target: Annotated[
str,
typer.Argument(help='The name of the build target/executable to run'),
],
configuration: Annotated[
str | None,
typer.Option(help='Named build configuration to use (e.g. CMake preset name, Meson build directory)'),
] = None,
) -> None:
"""Run a built executable
Assumes dependencies have been installed via `install`.
Args:
context: The CLI configuration object
target: The name of the build target to run
configuration: Optional named configuration
"""
with _session_project(context) as project:
project.run(target, configuration=configuration)